babylon.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899
  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. * @param options defines an option object to be sent to the requestFullscreen function
  12713. */
  12714. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12715. if (this.isFullscreen) {
  12716. BABYLON.Tools.ExitFullscreen();
  12717. }
  12718. else {
  12719. this._pointerLockRequested = requestPointerLock;
  12720. if (this._renderingCanvas) {
  12721. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12722. }
  12723. }
  12724. };
  12725. /**
  12726. * Clear the current render buffer or the current render target (if any is set up)
  12727. * @param color defines the color to use
  12728. * @param backBuffer defines if the back buffer must be cleared
  12729. * @param depth defines if the depth buffer must be cleared
  12730. * @param stencil defines if the stencil buffer must be cleared
  12731. */
  12732. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12733. if (stencil === void 0) { stencil = false; }
  12734. this.applyStates();
  12735. var mode = 0;
  12736. if (backBuffer && color) {
  12737. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12738. mode |= this._gl.COLOR_BUFFER_BIT;
  12739. }
  12740. if (depth) {
  12741. this._gl.clearDepth(1.0);
  12742. mode |= this._gl.DEPTH_BUFFER_BIT;
  12743. }
  12744. if (stencil) {
  12745. this._gl.clearStencil(0);
  12746. mode |= this._gl.STENCIL_BUFFER_BIT;
  12747. }
  12748. this._gl.clear(mode);
  12749. };
  12750. /**
  12751. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12752. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12753. * @param y defines the y-coordinate of the corner of the clear rectangle
  12754. * @param width defines the width of the clear rectangle
  12755. * @param height defines the height of the clear rectangle
  12756. * @param clearColor defines the clear color
  12757. */
  12758. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12759. var gl = this._gl;
  12760. // Save state
  12761. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12762. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12763. // Change state
  12764. gl.enable(gl.SCISSOR_TEST);
  12765. gl.scissor(x, y, width, height);
  12766. // Clear
  12767. this.clear(clearColor, true, true, true);
  12768. // Restore state
  12769. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12770. if (curScissor === true) {
  12771. gl.enable(gl.SCISSOR_TEST);
  12772. }
  12773. else {
  12774. gl.disable(gl.SCISSOR_TEST);
  12775. }
  12776. };
  12777. /** @hidden */
  12778. Engine.prototype._viewport = function (x, y, width, height) {
  12779. if (x !== this._viewportCached.x ||
  12780. y !== this._viewportCached.y ||
  12781. width !== this._viewportCached.z ||
  12782. height !== this._viewportCached.w) {
  12783. this._viewportCached.x = x;
  12784. this._viewportCached.y = y;
  12785. this._viewportCached.z = width;
  12786. this._viewportCached.w = height;
  12787. this._gl.viewport(x, y, width, height);
  12788. }
  12789. };
  12790. /**
  12791. * Set the WebGL's viewport
  12792. * @param viewport defines the viewport element to be used
  12793. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12794. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12795. */
  12796. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12797. var width = requiredWidth || this.getRenderWidth();
  12798. var height = requiredHeight || this.getRenderHeight();
  12799. var x = viewport.x || 0;
  12800. var y = viewport.y || 0;
  12801. this._cachedViewport = viewport;
  12802. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12803. };
  12804. /**
  12805. * Directly set the WebGL Viewport
  12806. * @param x defines the x coordinate of the viewport (in screen space)
  12807. * @param y defines the y coordinate of the viewport (in screen space)
  12808. * @param width defines the width of the viewport (in screen space)
  12809. * @param height defines the height of the viewport (in screen space)
  12810. * @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
  12811. */
  12812. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12813. var currentViewport = this._cachedViewport;
  12814. this._cachedViewport = null;
  12815. this._viewport(x, y, width, height);
  12816. return currentViewport;
  12817. };
  12818. /**
  12819. * Begin a new frame
  12820. */
  12821. Engine.prototype.beginFrame = function () {
  12822. this.onBeginFrameObservable.notifyObservers(this);
  12823. this._measureFps();
  12824. };
  12825. /**
  12826. * Enf the current frame
  12827. */
  12828. Engine.prototype.endFrame = function () {
  12829. // Force a flush in case we are using a bad OS.
  12830. if (this._badOS) {
  12831. this.flushFramebuffer();
  12832. }
  12833. // Submit frame to the vr device, if enabled
  12834. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12835. // TODO: We should only submit the frame if we read frameData successfully.
  12836. this._vrDisplay.submitFrame();
  12837. }
  12838. this.onEndFrameObservable.notifyObservers(this);
  12839. };
  12840. /**
  12841. * Resize the view according to the canvas' size
  12842. */
  12843. Engine.prototype.resize = function () {
  12844. // We're not resizing the size of the canvas while in VR mode & presenting
  12845. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12846. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12847. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12848. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12849. }
  12850. };
  12851. /**
  12852. * Force a specific size of the canvas
  12853. * @param width defines the new canvas' width
  12854. * @param height defines the new canvas' height
  12855. */
  12856. Engine.prototype.setSize = function (width, height) {
  12857. if (!this._renderingCanvas) {
  12858. return;
  12859. }
  12860. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12861. return;
  12862. }
  12863. this._renderingCanvas.width = width;
  12864. this._renderingCanvas.height = height;
  12865. for (var index = 0; index < this.scenes.length; index++) {
  12866. var scene = this.scenes[index];
  12867. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12868. var cam = scene.cameras[camIndex];
  12869. cam._currentRenderId = 0;
  12870. }
  12871. }
  12872. if (this.onResizeObservable.hasObservers) {
  12873. this.onResizeObservable.notifyObservers(this);
  12874. }
  12875. };
  12876. // WebVR functions
  12877. /**
  12878. * Gets a boolean indicating if a webVR device was detected
  12879. * @returns true if a webVR device was detected
  12880. */
  12881. Engine.prototype.isVRDevicePresent = function () {
  12882. return !!this._vrDisplay;
  12883. };
  12884. /**
  12885. * Gets the current webVR device
  12886. * @returns the current webVR device (or null)
  12887. */
  12888. Engine.prototype.getVRDevice = function () {
  12889. return this._vrDisplay;
  12890. };
  12891. /**
  12892. * Initializes a webVR display and starts listening to display change events
  12893. * The onVRDisplayChangedObservable will be notified upon these changes
  12894. * @returns The onVRDisplayChangedObservable
  12895. */
  12896. Engine.prototype.initWebVR = function () {
  12897. this.initWebVRAsync();
  12898. return this.onVRDisplayChangedObservable;
  12899. };
  12900. /**
  12901. * Initializes a webVR display and starts listening to display change events
  12902. * The onVRDisplayChangedObservable will be notified upon these changes
  12903. * @returns A promise containing a VRDisplay and if vr is supported
  12904. */
  12905. Engine.prototype.initWebVRAsync = function () {
  12906. var _this = this;
  12907. var notifyObservers = function () {
  12908. var eventArgs = {
  12909. vrDisplay: _this._vrDisplay,
  12910. vrSupported: _this._vrSupported
  12911. };
  12912. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12913. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12914. };
  12915. if (!this._onVrDisplayConnect) {
  12916. this._onVrDisplayConnect = function (event) {
  12917. _this._vrDisplay = event.display;
  12918. notifyObservers();
  12919. };
  12920. this._onVrDisplayDisconnect = function () {
  12921. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12922. _this._vrDisplay = undefined;
  12923. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12924. notifyObservers();
  12925. };
  12926. this._onVrDisplayPresentChange = function () {
  12927. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12928. };
  12929. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12930. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12931. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12932. }
  12933. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12934. this._webVRInitPromise.then(notifyObservers);
  12935. return this._webVRInitPromise;
  12936. };
  12937. /**
  12938. * Call this function to switch to webVR mode
  12939. * Will do nothing if webVR is not supported or if there is no webVR device
  12940. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12941. */
  12942. Engine.prototype.enableVR = function () {
  12943. var _this = this;
  12944. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12945. var onResolved = function () {
  12946. _this.onVRRequestPresentComplete.notifyObservers(true);
  12947. _this._onVRFullScreenTriggered();
  12948. };
  12949. var onRejected = function () {
  12950. _this.onVRRequestPresentComplete.notifyObservers(false);
  12951. };
  12952. this.onVRRequestPresentStart.notifyObservers(this);
  12953. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12954. }
  12955. };
  12956. /**
  12957. * Call this function to leave webVR mode
  12958. * Will do nothing if webVR is not supported or if there is no webVR device
  12959. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12960. */
  12961. Engine.prototype.disableVR = function () {
  12962. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12963. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12964. }
  12965. };
  12966. Engine.prototype._getVRDisplaysAsync = function () {
  12967. var _this = this;
  12968. return new Promise(function (res, rej) {
  12969. if (navigator.getVRDisplays) {
  12970. navigator.getVRDisplays().then(function (devices) {
  12971. _this._vrSupported = true;
  12972. // note that devices may actually be an empty array. This is fine;
  12973. // we expect this._vrDisplay to be undefined in this case.
  12974. _this._vrDisplay = devices[0];
  12975. res({
  12976. vrDisplay: _this._vrDisplay,
  12977. vrSupported: _this._vrSupported
  12978. });
  12979. });
  12980. }
  12981. else {
  12982. _this._vrDisplay = undefined;
  12983. _this._vrSupported = false;
  12984. res({
  12985. vrDisplay: _this._vrDisplay,
  12986. vrSupported: _this._vrSupported
  12987. });
  12988. }
  12989. });
  12990. };
  12991. /**
  12992. * Binds the frame buffer to the specified texture.
  12993. * @param texture The texture to render to or null for the default canvas
  12994. * @param faceIndex The face of the texture to render to in case of cube texture
  12995. * @param requiredWidth The width of the target to render to
  12996. * @param requiredHeight The height of the target to render to
  12997. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12998. * @param depthStencilTexture The depth stencil texture to use to render
  12999. * @param lodLevel defines le lod level to bind to the frame buffer
  13000. */
  13001. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13002. if (lodLevel === void 0) { lodLevel = 0; }
  13003. if (this._currentRenderTarget) {
  13004. this.unBindFramebuffer(this._currentRenderTarget);
  13005. }
  13006. this._currentRenderTarget = texture;
  13007. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13008. var gl = this._gl;
  13009. if (texture.isCube) {
  13010. if (faceIndex === undefined) {
  13011. faceIndex = 0;
  13012. }
  13013. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13014. if (depthStencilTexture) {
  13015. if (depthStencilTexture._generateStencilBuffer) {
  13016. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13017. }
  13018. else {
  13019. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13020. }
  13021. }
  13022. }
  13023. if (this._cachedViewport && !forceFullscreenViewport) {
  13024. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13025. }
  13026. else {
  13027. if (!requiredWidth) {
  13028. requiredWidth = texture.width;
  13029. if (lodLevel) {
  13030. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13031. }
  13032. }
  13033. if (!requiredHeight) {
  13034. requiredHeight = texture.height;
  13035. if (lodLevel) {
  13036. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13037. }
  13038. }
  13039. this._viewport(0, 0, requiredWidth, requiredHeight);
  13040. }
  13041. this.wipeCaches();
  13042. };
  13043. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13044. if (this._currentFramebuffer !== framebuffer) {
  13045. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13046. this._currentFramebuffer = framebuffer;
  13047. }
  13048. };
  13049. /**
  13050. * Unbind the current render target texture from the webGL context
  13051. * @param texture defines the render target texture to unbind
  13052. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13053. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13054. */
  13055. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13056. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13057. this._currentRenderTarget = null;
  13058. // If MSAA, we need to bitblt back to main texture
  13059. var gl = this._gl;
  13060. if (texture._MSAAFramebuffer) {
  13061. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13062. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13063. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13064. }
  13065. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13066. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13067. gl.generateMipmap(gl.TEXTURE_2D);
  13068. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13069. }
  13070. if (onBeforeUnbind) {
  13071. if (texture._MSAAFramebuffer) {
  13072. // Bind the correct framebuffer
  13073. this.bindUnboundFramebuffer(texture._framebuffer);
  13074. }
  13075. onBeforeUnbind();
  13076. }
  13077. this.bindUnboundFramebuffer(null);
  13078. };
  13079. /**
  13080. * Unbind a list of render target textures from the webGL context
  13081. * This is used only when drawBuffer extension or webGL2 are active
  13082. * @param textures defines the render target textures to unbind
  13083. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13084. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13085. */
  13086. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13087. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13088. this._currentRenderTarget = null;
  13089. // If MSAA, we need to bitblt back to main texture
  13090. var gl = this._gl;
  13091. if (textures[0]._MSAAFramebuffer) {
  13092. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13093. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13094. var attachments = textures[0]._attachments;
  13095. if (!attachments) {
  13096. attachments = new Array(textures.length);
  13097. textures[0]._attachments = attachments;
  13098. }
  13099. for (var i = 0; i < textures.length; i++) {
  13100. var texture = textures[i];
  13101. for (var j = 0; j < attachments.length; j++) {
  13102. attachments[j] = gl.NONE;
  13103. }
  13104. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13105. gl.readBuffer(attachments[i]);
  13106. gl.drawBuffers(attachments);
  13107. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13108. }
  13109. for (var i = 0; i < attachments.length; i++) {
  13110. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13111. }
  13112. gl.drawBuffers(attachments);
  13113. }
  13114. for (var i = 0; i < textures.length; i++) {
  13115. var texture = textures[i];
  13116. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13117. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13118. gl.generateMipmap(gl.TEXTURE_2D);
  13119. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13120. }
  13121. }
  13122. if (onBeforeUnbind) {
  13123. if (textures[0]._MSAAFramebuffer) {
  13124. // Bind the correct framebuffer
  13125. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13126. }
  13127. onBeforeUnbind();
  13128. }
  13129. this.bindUnboundFramebuffer(null);
  13130. };
  13131. /**
  13132. * Force the mipmap generation for the given render target texture
  13133. * @param texture defines the render target texture to use
  13134. */
  13135. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13136. if (texture.generateMipMaps) {
  13137. var gl = this._gl;
  13138. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13139. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13140. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13141. }
  13142. };
  13143. /**
  13144. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13145. */
  13146. Engine.prototype.flushFramebuffer = function () {
  13147. this._gl.flush();
  13148. };
  13149. /**
  13150. * Unbind the current render target and bind the default framebuffer
  13151. */
  13152. Engine.prototype.restoreDefaultFramebuffer = function () {
  13153. if (this._currentRenderTarget) {
  13154. this.unBindFramebuffer(this._currentRenderTarget);
  13155. }
  13156. else {
  13157. this.bindUnboundFramebuffer(null);
  13158. }
  13159. if (this._cachedViewport) {
  13160. this.setViewport(this._cachedViewport);
  13161. }
  13162. this.wipeCaches();
  13163. };
  13164. // UBOs
  13165. /**
  13166. * Create an uniform buffer
  13167. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13168. * @param elements defines the content of the uniform buffer
  13169. * @returns the webGL uniform buffer
  13170. */
  13171. Engine.prototype.createUniformBuffer = function (elements) {
  13172. var ubo = this._gl.createBuffer();
  13173. if (!ubo) {
  13174. throw new Error("Unable to create uniform buffer");
  13175. }
  13176. this.bindUniformBuffer(ubo);
  13177. if (elements instanceof Float32Array) {
  13178. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13179. }
  13180. else {
  13181. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13182. }
  13183. this.bindUniformBuffer(null);
  13184. ubo.references = 1;
  13185. return ubo;
  13186. };
  13187. /**
  13188. * Create a dynamic uniform buffer
  13189. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13190. * @param elements defines the content of the uniform buffer
  13191. * @returns the webGL uniform buffer
  13192. */
  13193. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13194. var ubo = this._gl.createBuffer();
  13195. if (!ubo) {
  13196. throw new Error("Unable to create dynamic uniform buffer");
  13197. }
  13198. this.bindUniformBuffer(ubo);
  13199. if (elements instanceof Float32Array) {
  13200. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13201. }
  13202. else {
  13203. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13204. }
  13205. this.bindUniformBuffer(null);
  13206. ubo.references = 1;
  13207. return ubo;
  13208. };
  13209. /**
  13210. * Update an existing uniform buffer
  13211. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13212. * @param uniformBuffer defines the target uniform buffer
  13213. * @param elements defines the content to update
  13214. * @param offset defines the offset in the uniform buffer where update should start
  13215. * @param count defines the size of the data to update
  13216. */
  13217. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13218. this.bindUniformBuffer(uniformBuffer);
  13219. if (offset === undefined) {
  13220. offset = 0;
  13221. }
  13222. if (count === undefined) {
  13223. if (elements instanceof Float32Array) {
  13224. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13225. }
  13226. else {
  13227. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13228. }
  13229. }
  13230. else {
  13231. if (elements instanceof Float32Array) {
  13232. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13233. }
  13234. else {
  13235. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13236. }
  13237. }
  13238. this.bindUniformBuffer(null);
  13239. };
  13240. // VBOs
  13241. Engine.prototype._resetVertexBufferBinding = function () {
  13242. this.bindArrayBuffer(null);
  13243. this._cachedVertexBuffers = null;
  13244. };
  13245. /**
  13246. * Creates a vertex buffer
  13247. * @param data the data for the vertex buffer
  13248. * @returns the new WebGL static buffer
  13249. */
  13250. Engine.prototype.createVertexBuffer = function (data) {
  13251. var vbo = this._gl.createBuffer();
  13252. if (!vbo) {
  13253. throw new Error("Unable to create vertex buffer");
  13254. }
  13255. this.bindArrayBuffer(vbo);
  13256. if (data instanceof Array) {
  13257. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13258. }
  13259. else {
  13260. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13261. }
  13262. this._resetVertexBufferBinding();
  13263. vbo.references = 1;
  13264. return vbo;
  13265. };
  13266. /**
  13267. * Creates a dynamic vertex buffer
  13268. * @param data the data for the dynamic vertex buffer
  13269. * @returns the new WebGL dynamic buffer
  13270. */
  13271. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13272. var vbo = this._gl.createBuffer();
  13273. if (!vbo) {
  13274. throw new Error("Unable to create dynamic vertex buffer");
  13275. }
  13276. this.bindArrayBuffer(vbo);
  13277. if (data instanceof Array) {
  13278. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13279. }
  13280. else {
  13281. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13282. }
  13283. this._resetVertexBufferBinding();
  13284. vbo.references = 1;
  13285. return vbo;
  13286. };
  13287. /**
  13288. * Update a dynamic index buffer
  13289. * @param indexBuffer defines the target index buffer
  13290. * @param indices defines the data to update
  13291. * @param offset defines the offset in the target index buffer where update should start
  13292. */
  13293. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13294. if (offset === void 0) { offset = 0; }
  13295. // Force cache update
  13296. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13297. this.bindIndexBuffer(indexBuffer);
  13298. var arrayBuffer;
  13299. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13300. arrayBuffer = indices;
  13301. }
  13302. else {
  13303. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13304. }
  13305. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13306. this._resetIndexBufferBinding();
  13307. };
  13308. /**
  13309. * Updates a dynamic vertex buffer.
  13310. * @param vertexBuffer the vertex buffer to update
  13311. * @param data the data used to update the vertex buffer
  13312. * @param byteOffset the byte offset of the data
  13313. * @param byteLength the byte length of the data
  13314. */
  13315. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13316. this.bindArrayBuffer(vertexBuffer);
  13317. if (byteOffset === undefined) {
  13318. byteOffset = 0;
  13319. }
  13320. if (byteLength === undefined) {
  13321. if (data instanceof Array) {
  13322. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13323. }
  13324. else {
  13325. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13326. }
  13327. }
  13328. else {
  13329. if (data instanceof Array) {
  13330. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13331. }
  13332. else {
  13333. if (data instanceof ArrayBuffer) {
  13334. data = new Uint8Array(data, byteOffset, byteLength);
  13335. }
  13336. else {
  13337. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13338. }
  13339. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13340. }
  13341. }
  13342. this._resetVertexBufferBinding();
  13343. };
  13344. Engine.prototype._resetIndexBufferBinding = function () {
  13345. this.bindIndexBuffer(null);
  13346. this._cachedIndexBuffer = null;
  13347. };
  13348. /**
  13349. * Creates a new index buffer
  13350. * @param indices defines the content of the index buffer
  13351. * @param updatable defines if the index buffer must be updatable
  13352. * @returns a new webGL buffer
  13353. */
  13354. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13355. var vbo = this._gl.createBuffer();
  13356. if (!vbo) {
  13357. throw new Error("Unable to create index buffer");
  13358. }
  13359. this.bindIndexBuffer(vbo);
  13360. // Check for 32 bits indices
  13361. var arrayBuffer;
  13362. var need32Bits = false;
  13363. if (indices instanceof Uint16Array) {
  13364. arrayBuffer = indices;
  13365. }
  13366. else {
  13367. //check 32 bit support
  13368. if (this._caps.uintIndices) {
  13369. if (indices instanceof Uint32Array) {
  13370. arrayBuffer = indices;
  13371. need32Bits = true;
  13372. }
  13373. else {
  13374. //number[] or Int32Array, check if 32 bit is necessary
  13375. for (var index = 0; index < indices.length; index++) {
  13376. if (indices[index] > 65535) {
  13377. need32Bits = true;
  13378. break;
  13379. }
  13380. }
  13381. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13382. }
  13383. }
  13384. else {
  13385. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13386. arrayBuffer = new Uint16Array(indices);
  13387. }
  13388. }
  13389. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13390. this._resetIndexBufferBinding();
  13391. vbo.references = 1;
  13392. vbo.is32Bits = need32Bits;
  13393. return vbo;
  13394. };
  13395. /**
  13396. * Bind a webGL buffer to the webGL context
  13397. * @param buffer defines the buffer to bind
  13398. */
  13399. Engine.prototype.bindArrayBuffer = function (buffer) {
  13400. if (!this._vaoRecordInProgress) {
  13401. this._unbindVertexArrayObject();
  13402. }
  13403. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13404. };
  13405. /**
  13406. * Bind an uniform buffer to the current webGL context
  13407. * @param buffer defines the buffer to bind
  13408. */
  13409. Engine.prototype.bindUniformBuffer = function (buffer) {
  13410. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13411. };
  13412. /**
  13413. * Bind a buffer to the current webGL context at a given location
  13414. * @param buffer defines the buffer to bind
  13415. * @param location defines the index where to bind the buffer
  13416. */
  13417. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13418. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13419. };
  13420. /**
  13421. * Bind a specific block at a given index in a specific shader program
  13422. * @param shaderProgram defines the shader program
  13423. * @param blockName defines the block name
  13424. * @param index defines the index where to bind the block
  13425. */
  13426. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13427. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13428. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13429. };
  13430. ;
  13431. Engine.prototype.bindIndexBuffer = function (buffer) {
  13432. if (!this._vaoRecordInProgress) {
  13433. this._unbindVertexArrayObject();
  13434. }
  13435. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13436. };
  13437. Engine.prototype.bindBuffer = function (buffer, target) {
  13438. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13439. this._gl.bindBuffer(target, buffer);
  13440. this._currentBoundBuffer[target] = buffer;
  13441. }
  13442. };
  13443. /**
  13444. * update the bound buffer with the given data
  13445. * @param data defines the data to update
  13446. */
  13447. Engine.prototype.updateArrayBuffer = function (data) {
  13448. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13449. };
  13450. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13451. var pointer = this._currentBufferPointers[indx];
  13452. var changed = false;
  13453. if (!pointer.active) {
  13454. changed = true;
  13455. pointer.active = true;
  13456. pointer.index = indx;
  13457. pointer.size = size;
  13458. pointer.type = type;
  13459. pointer.normalized = normalized;
  13460. pointer.stride = stride;
  13461. pointer.offset = offset;
  13462. pointer.buffer = buffer;
  13463. }
  13464. else {
  13465. if (pointer.buffer !== buffer) {
  13466. pointer.buffer = buffer;
  13467. changed = true;
  13468. }
  13469. if (pointer.size !== size) {
  13470. pointer.size = size;
  13471. changed = true;
  13472. }
  13473. if (pointer.type !== type) {
  13474. pointer.type = type;
  13475. changed = true;
  13476. }
  13477. if (pointer.normalized !== normalized) {
  13478. pointer.normalized = normalized;
  13479. changed = true;
  13480. }
  13481. if (pointer.stride !== stride) {
  13482. pointer.stride = stride;
  13483. changed = true;
  13484. }
  13485. if (pointer.offset !== offset) {
  13486. pointer.offset = offset;
  13487. changed = true;
  13488. }
  13489. }
  13490. if (changed || this._vaoRecordInProgress) {
  13491. this.bindArrayBuffer(buffer);
  13492. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13493. }
  13494. };
  13495. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13496. if (indexBuffer == null) {
  13497. return;
  13498. }
  13499. if (this._cachedIndexBuffer !== indexBuffer) {
  13500. this._cachedIndexBuffer = indexBuffer;
  13501. this.bindIndexBuffer(indexBuffer);
  13502. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13503. }
  13504. };
  13505. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13506. var attributes = effect.getAttributesNames();
  13507. if (!this._vaoRecordInProgress) {
  13508. this._unbindVertexArrayObject();
  13509. }
  13510. this.unbindAllAttributes();
  13511. for (var index = 0; index < attributes.length; index++) {
  13512. var order = effect.getAttributeLocation(index);
  13513. if (order >= 0) {
  13514. var vertexBuffer = vertexBuffers[attributes[index]];
  13515. if (!vertexBuffer) {
  13516. continue;
  13517. }
  13518. this._gl.enableVertexAttribArray(order);
  13519. if (!this._vaoRecordInProgress) {
  13520. this._vertexAttribArraysEnabled[order] = true;
  13521. }
  13522. var buffer = vertexBuffer.getBuffer();
  13523. if (buffer) {
  13524. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13525. if (vertexBuffer.getIsInstanced()) {
  13526. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13527. if (!this._vaoRecordInProgress) {
  13528. this._currentInstanceLocations.push(order);
  13529. this._currentInstanceBuffers.push(buffer);
  13530. }
  13531. }
  13532. }
  13533. }
  13534. }
  13535. };
  13536. /**
  13537. * Records a vertex array object
  13538. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13539. * @param vertexBuffers defines the list of vertex buffers to store
  13540. * @param indexBuffer defines the index buffer to store
  13541. * @param effect defines the effect to store
  13542. * @returns the new vertex array object
  13543. */
  13544. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13545. var vao = this._gl.createVertexArray();
  13546. this._vaoRecordInProgress = true;
  13547. this._gl.bindVertexArray(vao);
  13548. this._mustWipeVertexAttributes = true;
  13549. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13550. this.bindIndexBuffer(indexBuffer);
  13551. this._vaoRecordInProgress = false;
  13552. this._gl.bindVertexArray(null);
  13553. return vao;
  13554. };
  13555. /**
  13556. * Bind a specific vertex array object
  13557. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13558. * @param vertexArrayObject defines the vertex array object to bind
  13559. * @param indexBuffer defines the index buffer to bind
  13560. */
  13561. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13562. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13563. this._cachedVertexArrayObject = vertexArrayObject;
  13564. this._gl.bindVertexArray(vertexArrayObject);
  13565. this._cachedVertexBuffers = null;
  13566. this._cachedIndexBuffer = null;
  13567. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13568. this._mustWipeVertexAttributes = true;
  13569. }
  13570. };
  13571. /**
  13572. * Bind webGl buffers directly to the webGL context
  13573. * @param vertexBuffer defines the vertex buffer to bind
  13574. * @param indexBuffer defines the index buffer to bind
  13575. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13576. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13577. * @param effect defines the effect associated with the vertex buffer
  13578. */
  13579. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13580. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13581. this._cachedVertexBuffers = vertexBuffer;
  13582. this._cachedEffectForVertexBuffers = effect;
  13583. var attributesCount = effect.getAttributesCount();
  13584. this._unbindVertexArrayObject();
  13585. this.unbindAllAttributes();
  13586. var offset = 0;
  13587. for (var index = 0; index < attributesCount; index++) {
  13588. if (index < vertexDeclaration.length) {
  13589. var order = effect.getAttributeLocation(index);
  13590. if (order >= 0) {
  13591. this._gl.enableVertexAttribArray(order);
  13592. this._vertexAttribArraysEnabled[order] = true;
  13593. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13594. }
  13595. offset += vertexDeclaration[index] * 4;
  13596. }
  13597. }
  13598. }
  13599. this._bindIndexBufferWithCache(indexBuffer);
  13600. };
  13601. Engine.prototype._unbindVertexArrayObject = function () {
  13602. if (!this._cachedVertexArrayObject) {
  13603. return;
  13604. }
  13605. this._cachedVertexArrayObject = null;
  13606. this._gl.bindVertexArray(null);
  13607. };
  13608. /**
  13609. * Bind a list of vertex buffers to the webGL context
  13610. * @param vertexBuffers defines the list of vertex buffers to bind
  13611. * @param indexBuffer defines the index buffer to bind
  13612. * @param effect defines the effect associated with the vertex buffers
  13613. */
  13614. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13615. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13616. this._cachedVertexBuffers = vertexBuffers;
  13617. this._cachedEffectForVertexBuffers = effect;
  13618. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13619. }
  13620. this._bindIndexBufferWithCache(indexBuffer);
  13621. };
  13622. /**
  13623. * Unbind all instance attributes
  13624. */
  13625. Engine.prototype.unbindInstanceAttributes = function () {
  13626. var boundBuffer;
  13627. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13628. var instancesBuffer = this._currentInstanceBuffers[i];
  13629. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13630. boundBuffer = instancesBuffer;
  13631. this.bindArrayBuffer(instancesBuffer);
  13632. }
  13633. var offsetLocation = this._currentInstanceLocations[i];
  13634. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13635. }
  13636. this._currentInstanceBuffers.length = 0;
  13637. this._currentInstanceLocations.length = 0;
  13638. };
  13639. /**
  13640. * Release and free the memory of a vertex array object
  13641. * @param vao defines the vertex array object to delete
  13642. */
  13643. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13644. this._gl.deleteVertexArray(vao);
  13645. };
  13646. /** @hidden */
  13647. Engine.prototype._releaseBuffer = function (buffer) {
  13648. buffer.references--;
  13649. if (buffer.references === 0) {
  13650. this._gl.deleteBuffer(buffer);
  13651. return true;
  13652. }
  13653. return false;
  13654. };
  13655. /**
  13656. * Creates a webGL buffer to use with instanciation
  13657. * @param capacity defines the size of the buffer
  13658. * @returns the webGL buffer
  13659. */
  13660. Engine.prototype.createInstancesBuffer = function (capacity) {
  13661. var buffer = this._gl.createBuffer();
  13662. if (!buffer) {
  13663. throw new Error("Unable to create instance buffer");
  13664. }
  13665. buffer.capacity = capacity;
  13666. this.bindArrayBuffer(buffer);
  13667. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13668. return buffer;
  13669. };
  13670. /**
  13671. * Delete a webGL buffer used with instanciation
  13672. * @param buffer defines the webGL buffer to delete
  13673. */
  13674. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13675. this._gl.deleteBuffer(buffer);
  13676. };
  13677. /**
  13678. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13679. * @param instancesBuffer defines the webGL buffer to update and bind
  13680. * @param data defines the data to store in the buffer
  13681. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13682. */
  13683. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13684. this.bindArrayBuffer(instancesBuffer);
  13685. if (data) {
  13686. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13687. }
  13688. if (offsetLocations[0].index !== undefined) {
  13689. var stride = 0;
  13690. for (var i = 0; i < offsetLocations.length; i++) {
  13691. var ai = offsetLocations[i];
  13692. stride += ai.attributeSize * 4;
  13693. }
  13694. for (var i = 0; i < offsetLocations.length; i++) {
  13695. var ai = offsetLocations[i];
  13696. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13697. this._gl.enableVertexAttribArray(ai.index);
  13698. this._vertexAttribArraysEnabled[ai.index] = true;
  13699. }
  13700. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13701. this._gl.vertexAttribDivisor(ai.index, 1);
  13702. this._currentInstanceLocations.push(ai.index);
  13703. this._currentInstanceBuffers.push(instancesBuffer);
  13704. }
  13705. }
  13706. else {
  13707. for (var index = 0; index < 4; index++) {
  13708. var offsetLocation = offsetLocations[index];
  13709. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13710. this._gl.enableVertexAttribArray(offsetLocation);
  13711. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13712. }
  13713. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13714. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13715. this._currentInstanceLocations.push(offsetLocation);
  13716. this._currentInstanceBuffers.push(instancesBuffer);
  13717. }
  13718. }
  13719. };
  13720. /**
  13721. * Apply all cached states (depth, culling, stencil and alpha)
  13722. */
  13723. Engine.prototype.applyStates = function () {
  13724. this._depthCullingState.apply(this._gl);
  13725. this._stencilState.apply(this._gl);
  13726. this._alphaState.apply(this._gl);
  13727. };
  13728. /**
  13729. * Send a draw order
  13730. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13731. * @param indexStart defines the starting index
  13732. * @param indexCount defines the number of index to draw
  13733. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13734. */
  13735. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13736. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13737. };
  13738. /**
  13739. * Draw a list of points
  13740. * @param verticesStart defines the index of first vertex to draw
  13741. * @param verticesCount defines the count of vertices to draw
  13742. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13743. */
  13744. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13745. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13746. };
  13747. /**
  13748. * Draw a list of unindexed primitives
  13749. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13750. * @param verticesStart defines the index of first vertex to draw
  13751. * @param verticesCount defines the count of vertices to draw
  13752. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13753. */
  13754. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13755. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13756. };
  13757. /**
  13758. * Draw a list of indexed primitives
  13759. * @param fillMode defines the primitive to use
  13760. * @param indexStart defines the starting index
  13761. * @param indexCount defines the number of index to draw
  13762. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13763. */
  13764. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13765. // Apply states
  13766. this.applyStates();
  13767. this._drawCalls.addCount(1, false);
  13768. // Render
  13769. var drawMode = this._drawMode(fillMode);
  13770. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13771. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13772. if (instancesCount) {
  13773. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13774. }
  13775. else {
  13776. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13777. }
  13778. };
  13779. /**
  13780. * Draw a list of unindexed primitives
  13781. * @param fillMode defines the primitive to use
  13782. * @param verticesStart defines the index of first vertex to draw
  13783. * @param verticesCount defines the count of vertices to draw
  13784. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13785. */
  13786. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13787. // Apply states
  13788. this.applyStates();
  13789. this._drawCalls.addCount(1, false);
  13790. var drawMode = this._drawMode(fillMode);
  13791. if (instancesCount) {
  13792. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13793. }
  13794. else {
  13795. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13796. }
  13797. };
  13798. Engine.prototype._drawMode = function (fillMode) {
  13799. switch (fillMode) {
  13800. // Triangle views
  13801. case BABYLON.Material.TriangleFillMode:
  13802. return this._gl.TRIANGLES;
  13803. case BABYLON.Material.PointFillMode:
  13804. return this._gl.POINTS;
  13805. case BABYLON.Material.WireFrameFillMode:
  13806. return this._gl.LINES;
  13807. // Draw modes
  13808. case BABYLON.Material.PointListDrawMode:
  13809. return this._gl.POINTS;
  13810. case BABYLON.Material.LineListDrawMode:
  13811. return this._gl.LINES;
  13812. case BABYLON.Material.LineLoopDrawMode:
  13813. return this._gl.LINE_LOOP;
  13814. case BABYLON.Material.LineStripDrawMode:
  13815. return this._gl.LINE_STRIP;
  13816. case BABYLON.Material.TriangleStripDrawMode:
  13817. return this._gl.TRIANGLE_STRIP;
  13818. case BABYLON.Material.TriangleFanDrawMode:
  13819. return this._gl.TRIANGLE_FAN;
  13820. default:
  13821. return this._gl.TRIANGLES;
  13822. }
  13823. };
  13824. // Shaders
  13825. /** @hidden */
  13826. Engine.prototype._releaseEffect = function (effect) {
  13827. if (this._compiledEffects[effect._key]) {
  13828. delete this._compiledEffects[effect._key];
  13829. this._deleteProgram(effect.getProgram());
  13830. }
  13831. };
  13832. /** @hidden */
  13833. Engine.prototype._deleteProgram = function (program) {
  13834. if (program) {
  13835. program.__SPECTOR_rebuildProgram = null;
  13836. if (program.transformFeedback) {
  13837. this.deleteTransformFeedback(program.transformFeedback);
  13838. program.transformFeedback = null;
  13839. }
  13840. this._gl.deleteProgram(program);
  13841. }
  13842. };
  13843. /**
  13844. * Create a new effect (used to store vertex/fragment shaders)
  13845. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13846. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13847. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13848. * @param samplers defines an array of string used to represent textures
  13849. * @param defines defines the string containing the defines to use to compile the shaders
  13850. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13851. * @param onCompiled defines a function to call when the effect creation is successful
  13852. * @param onError defines a function to call when the effect creation has failed
  13853. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13854. * @returns the new Effect
  13855. */
  13856. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13857. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13858. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13859. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13860. if (this._compiledEffects[name]) {
  13861. var compiledEffect = this._compiledEffects[name];
  13862. if (onCompiled && compiledEffect.isReady()) {
  13863. onCompiled(compiledEffect);
  13864. }
  13865. return compiledEffect;
  13866. }
  13867. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13868. effect._key = name;
  13869. this._compiledEffects[name] = effect;
  13870. return effect;
  13871. };
  13872. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13873. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13874. };
  13875. ;
  13876. Engine.prototype._compileRawShader = function (source, type) {
  13877. var gl = this._gl;
  13878. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13879. gl.shaderSource(shader, source);
  13880. gl.compileShader(shader);
  13881. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13882. var log = gl.getShaderInfoLog(shader);
  13883. if (log) {
  13884. throw new Error(log);
  13885. }
  13886. }
  13887. if (!shader) {
  13888. throw new Error("Something went wrong while compile the shader.");
  13889. }
  13890. return shader;
  13891. };
  13892. ;
  13893. /**
  13894. * Directly creates a webGL program
  13895. * @param vertexCode defines the vertex shader code to use
  13896. * @param fragmentCode defines the fragment shader code to use
  13897. * @param context defines the webGL context to use (if not set, the current one will be used)
  13898. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13899. * @returns the new webGL program
  13900. */
  13901. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13902. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13903. context = context || this._gl;
  13904. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13905. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13906. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13907. };
  13908. /**
  13909. * Creates a webGL program
  13910. * @param vertexCode defines the vertex shader code to use
  13911. * @param fragmentCode defines the fragment shader code to use
  13912. * @param defines defines the string containing the defines to use to compile the shaders
  13913. * @param context defines the webGL context to use (if not set, the current one will be used)
  13914. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13915. * @returns the new webGL program
  13916. */
  13917. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13918. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13919. context = context || this._gl;
  13920. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13921. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13922. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13923. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13924. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13925. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13926. return program;
  13927. };
  13928. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13929. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13930. var shaderProgram = context.createProgram();
  13931. if (!shaderProgram) {
  13932. throw new Error("Unable to create program");
  13933. }
  13934. context.attachShader(shaderProgram, vertexShader);
  13935. context.attachShader(shaderProgram, fragmentShader);
  13936. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13937. var transformFeedback = this.createTransformFeedback();
  13938. this.bindTransformFeedback(transformFeedback);
  13939. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13940. shaderProgram.transformFeedback = transformFeedback;
  13941. }
  13942. context.linkProgram(shaderProgram);
  13943. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13944. this.bindTransformFeedback(null);
  13945. }
  13946. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13947. if (!linked) {
  13948. var error = context.getProgramInfoLog(shaderProgram);
  13949. if (error) {
  13950. throw new Error(error);
  13951. }
  13952. }
  13953. if (this.validateShaderPrograms) {
  13954. context.validateProgram(shaderProgram);
  13955. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13956. if (!validated) {
  13957. var error = context.getProgramInfoLog(shaderProgram);
  13958. if (error) {
  13959. throw new Error(error);
  13960. }
  13961. }
  13962. }
  13963. context.deleteShader(vertexShader);
  13964. context.deleteShader(fragmentShader);
  13965. return shaderProgram;
  13966. };
  13967. /**
  13968. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13969. * @param shaderProgram defines the webGL program to use
  13970. * @param uniformsNames defines the list of uniform names
  13971. * @returns an array of webGL uniform locations
  13972. */
  13973. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13974. var results = new Array();
  13975. for (var index = 0; index < uniformsNames.length; index++) {
  13976. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13977. }
  13978. return results;
  13979. };
  13980. /**
  13981. * Gets the lsit of active attributes for a given webGL program
  13982. * @param shaderProgram defines the webGL program to use
  13983. * @param attributesNames defines the list of attribute names to get
  13984. * @returns an array of indices indicating the offset of each attribute
  13985. */
  13986. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13987. var results = [];
  13988. for (var index = 0; index < attributesNames.length; index++) {
  13989. try {
  13990. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13991. }
  13992. catch (e) {
  13993. results.push(-1);
  13994. }
  13995. }
  13996. return results;
  13997. };
  13998. /**
  13999. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14000. * @param effect defines the effect to activate
  14001. */
  14002. Engine.prototype.enableEffect = function (effect) {
  14003. if (!effect || effect === this._currentEffect) {
  14004. return;
  14005. }
  14006. // Use program
  14007. this.bindSamplers(effect);
  14008. this._currentEffect = effect;
  14009. if (effect.onBind) {
  14010. effect.onBind(effect);
  14011. }
  14012. if (effect._onBindObservable) {
  14013. effect._onBindObservable.notifyObservers(effect);
  14014. }
  14015. };
  14016. /**
  14017. * Set the value of an uniform to an array of int32
  14018. * @param uniform defines the webGL uniform location where to store the value
  14019. * @param array defines the array of int32 to store
  14020. */
  14021. Engine.prototype.setIntArray = function (uniform, array) {
  14022. if (!uniform)
  14023. return;
  14024. this._gl.uniform1iv(uniform, array);
  14025. };
  14026. /**
  14027. * Set the value of an uniform to an array of int32 (stored as vec2)
  14028. * @param uniform defines the webGL uniform location where to store the value
  14029. * @param array defines the array of int32 to store
  14030. */
  14031. Engine.prototype.setIntArray2 = function (uniform, array) {
  14032. if (!uniform || array.length % 2 !== 0)
  14033. return;
  14034. this._gl.uniform2iv(uniform, array);
  14035. };
  14036. /**
  14037. * Set the value of an uniform to an array of int32 (stored as vec3)
  14038. * @param uniform defines the webGL uniform location where to store the value
  14039. * @param array defines the array of int32 to store
  14040. */
  14041. Engine.prototype.setIntArray3 = function (uniform, array) {
  14042. if (!uniform || array.length % 3 !== 0)
  14043. return;
  14044. this._gl.uniform3iv(uniform, array);
  14045. };
  14046. /**
  14047. * Set the value of an uniform to an array of int32 (stored as vec4)
  14048. * @param uniform defines the webGL uniform location where to store the value
  14049. * @param array defines the array of int32 to store
  14050. */
  14051. Engine.prototype.setIntArray4 = function (uniform, array) {
  14052. if (!uniform || array.length % 4 !== 0)
  14053. return;
  14054. this._gl.uniform4iv(uniform, array);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of float32
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param array defines the array of float32 to store
  14060. */
  14061. Engine.prototype.setFloatArray = function (uniform, array) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniform1fv(uniform, array);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to an array of float32 (stored as vec2)
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param array defines the array of float32 to store
  14070. */
  14071. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14072. if (!uniform || array.length % 2 !== 0)
  14073. return;
  14074. this._gl.uniform2fv(uniform, array);
  14075. };
  14076. /**
  14077. * Set the value of an uniform to an array of float32 (stored as vec3)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param array defines the array of float32 to store
  14080. */
  14081. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14082. if (!uniform || array.length % 3 !== 0)
  14083. return;
  14084. this._gl.uniform3fv(uniform, array);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to an array of float32 (stored as vec4)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param array defines the array of float32 to store
  14090. */
  14091. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14092. if (!uniform || array.length % 4 !== 0)
  14093. return;
  14094. this._gl.uniform4fv(uniform, array);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to an array of number
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param array defines the array of number to store
  14100. */
  14101. Engine.prototype.setArray = function (uniform, array) {
  14102. if (!uniform)
  14103. return;
  14104. this._gl.uniform1fv(uniform, array);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to an array of number (stored as vec2)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param array defines the array of number to store
  14110. */
  14111. Engine.prototype.setArray2 = function (uniform, array) {
  14112. if (!uniform || array.length % 2 !== 0)
  14113. return;
  14114. this._gl.uniform2fv(uniform, array);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to an array of number (stored as vec3)
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param array defines the array of number to store
  14120. */
  14121. Engine.prototype.setArray3 = function (uniform, array) {
  14122. if (!uniform || array.length % 3 !== 0)
  14123. return;
  14124. this._gl.uniform3fv(uniform, array);
  14125. };
  14126. /**
  14127. * Set the value of an uniform to an array of number (stored as vec4)
  14128. * @param uniform defines the webGL uniform location where to store the value
  14129. * @param array defines the array of number to store
  14130. */
  14131. Engine.prototype.setArray4 = function (uniform, array) {
  14132. if (!uniform || array.length % 4 !== 0)
  14133. return;
  14134. this._gl.uniform4fv(uniform, array);
  14135. };
  14136. /**
  14137. * Set the value of an uniform to an array of float32 (stored as matrices)
  14138. * @param uniform defines the webGL uniform location where to store the value
  14139. * @param matrices defines the array of float32 to store
  14140. */
  14141. Engine.prototype.setMatrices = function (uniform, matrices) {
  14142. if (!uniform)
  14143. return;
  14144. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14145. };
  14146. /**
  14147. * Set the value of an uniform to a matrix
  14148. * @param uniform defines the webGL uniform location where to store the value
  14149. * @param matrix defines the matrix to store
  14150. */
  14151. Engine.prototype.setMatrix = function (uniform, matrix) {
  14152. if (!uniform)
  14153. return;
  14154. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14155. };
  14156. /**
  14157. * Set the value of an uniform to a matrix (3x3)
  14158. * @param uniform defines the webGL uniform location where to store the value
  14159. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14160. */
  14161. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14162. if (!uniform)
  14163. return;
  14164. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14165. };
  14166. /**
  14167. * Set the value of an uniform to a matrix (2x2)
  14168. * @param uniform defines the webGL uniform location where to store the value
  14169. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14170. */
  14171. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14172. if (!uniform)
  14173. return;
  14174. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14175. };
  14176. /**
  14177. * Set the value of an uniform to a number (int)
  14178. * @param uniform defines the webGL uniform location where to store the value
  14179. * @param value defines the int number to store
  14180. */
  14181. Engine.prototype.setInt = function (uniform, value) {
  14182. if (!uniform)
  14183. return;
  14184. this._gl.uniform1i(uniform, value);
  14185. };
  14186. /**
  14187. * Set the value of an uniform to a number (float)
  14188. * @param uniform defines the webGL uniform location where to store the value
  14189. * @param value defines the float number to store
  14190. */
  14191. Engine.prototype.setFloat = function (uniform, value) {
  14192. if (!uniform)
  14193. return;
  14194. this._gl.uniform1f(uniform, value);
  14195. };
  14196. /**
  14197. * Set the value of an uniform to a vec2
  14198. * @param uniform defines the webGL uniform location where to store the value
  14199. * @param x defines the 1st component of the value
  14200. * @param y defines the 2nd component of the value
  14201. */
  14202. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14203. if (!uniform)
  14204. return;
  14205. this._gl.uniform2f(uniform, x, y);
  14206. };
  14207. /**
  14208. * Set the value of an uniform to a vec3
  14209. * @param uniform defines the webGL uniform location where to store the value
  14210. * @param x defines the 1st component of the value
  14211. * @param y defines the 2nd component of the value
  14212. * @param z defines the 3rd component of the value
  14213. */
  14214. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14215. if (!uniform)
  14216. return;
  14217. this._gl.uniform3f(uniform, x, y, z);
  14218. };
  14219. /**
  14220. * Set the value of an uniform to a boolean
  14221. * @param uniform defines the webGL uniform location where to store the value
  14222. * @param bool defines the boolean to store
  14223. */
  14224. Engine.prototype.setBool = function (uniform, bool) {
  14225. if (!uniform)
  14226. return;
  14227. this._gl.uniform1i(uniform, bool);
  14228. };
  14229. /**
  14230. * Set the value of an uniform to a vec4
  14231. * @param uniform defines the webGL uniform location where to store the value
  14232. * @param x defines the 1st component of the value
  14233. * @param y defines the 2nd component of the value
  14234. * @param z defines the 3rd component of the value
  14235. * @param w defines the 4th component of the value
  14236. */
  14237. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14238. if (!uniform)
  14239. return;
  14240. this._gl.uniform4f(uniform, x, y, z, w);
  14241. };
  14242. /**
  14243. * Set the value of an uniform to a Color3
  14244. * @param uniform defines the webGL uniform location where to store the value
  14245. * @param color3 defines the color to store
  14246. */
  14247. Engine.prototype.setColor3 = function (uniform, color3) {
  14248. if (!uniform)
  14249. return;
  14250. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14251. };
  14252. /**
  14253. * Set the value of an uniform to a Color3 and an alpha value
  14254. * @param uniform defines the webGL uniform location where to store the value
  14255. * @param color3 defines the color to store
  14256. * @param alpha defines the alpha component to store
  14257. */
  14258. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14259. if (!uniform)
  14260. return;
  14261. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14262. };
  14263. /**
  14264. * Sets a Color4 on a uniform variable
  14265. * @param uniform defines the uniform location
  14266. * @param color4 defines the value to be set
  14267. */
  14268. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14269. if (!uniform)
  14270. return;
  14271. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14272. };
  14273. // States
  14274. /**
  14275. * Set various states to the webGL context
  14276. * @param culling defines backface culling state
  14277. * @param zOffset defines the value to apply to zOffset (0 by default)
  14278. * @param force defines if states must be applied even if cache is up to date
  14279. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14280. */
  14281. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14282. if (zOffset === void 0) { zOffset = 0; }
  14283. if (reverseSide === void 0) { reverseSide = false; }
  14284. // Culling
  14285. if (this._depthCullingState.cull !== culling || force) {
  14286. this._depthCullingState.cull = culling;
  14287. }
  14288. // Cull face
  14289. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14290. if (this._depthCullingState.cullFace !== cullFace || force) {
  14291. this._depthCullingState.cullFace = cullFace;
  14292. }
  14293. // Z offset
  14294. this.setZOffset(zOffset);
  14295. // Front face
  14296. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14297. if (this._depthCullingState.frontFace !== frontFace || force) {
  14298. this._depthCullingState.frontFace = frontFace;
  14299. }
  14300. };
  14301. /**
  14302. * Set the z offset to apply to current rendering
  14303. * @param value defines the offset to apply
  14304. */
  14305. Engine.prototype.setZOffset = function (value) {
  14306. this._depthCullingState.zOffset = value;
  14307. };
  14308. /**
  14309. * Gets the current value of the zOffset
  14310. * @returns the current zOffset state
  14311. */
  14312. Engine.prototype.getZOffset = function () {
  14313. return this._depthCullingState.zOffset;
  14314. };
  14315. /**
  14316. * Enable or disable depth buffering
  14317. * @param enable defines the state to set
  14318. */
  14319. Engine.prototype.setDepthBuffer = function (enable) {
  14320. this._depthCullingState.depthTest = enable;
  14321. };
  14322. /**
  14323. * Gets a boolean indicating if depth writing is enabled
  14324. * @returns the current depth writing state
  14325. */
  14326. Engine.prototype.getDepthWrite = function () {
  14327. return this._depthCullingState.depthMask;
  14328. };
  14329. /**
  14330. * Enable or disable depth writing
  14331. * @param enable defines the state to set
  14332. */
  14333. Engine.prototype.setDepthWrite = function (enable) {
  14334. this._depthCullingState.depthMask = enable;
  14335. };
  14336. /**
  14337. * Enable or disable color writing
  14338. * @param enable defines the state to set
  14339. */
  14340. Engine.prototype.setColorWrite = function (enable) {
  14341. this._gl.colorMask(enable, enable, enable, enable);
  14342. this._colorWrite = enable;
  14343. };
  14344. /**
  14345. * Gets a boolean indicating if color writing is enabled
  14346. * @returns the current color writing state
  14347. */
  14348. Engine.prototype.getColorWrite = function () {
  14349. return this._colorWrite;
  14350. };
  14351. /**
  14352. * Sets alpha constants used by some alpha blending modes
  14353. * @param r defines the red component
  14354. * @param g defines the green component
  14355. * @param b defines the blue component
  14356. * @param a defines the alpha component
  14357. */
  14358. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14359. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14360. };
  14361. /**
  14362. * Sets the current alpha mode
  14363. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14364. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14365. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14366. */
  14367. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14368. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14369. if (this._alphaMode === mode) {
  14370. return;
  14371. }
  14372. switch (mode) {
  14373. case Engine.ALPHA_DISABLE:
  14374. this._alphaState.alphaBlend = false;
  14375. break;
  14376. case Engine.ALPHA_PREMULTIPLIED:
  14377. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14378. this._alphaState.alphaBlend = true;
  14379. break;
  14380. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14381. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14382. this._alphaState.alphaBlend = true;
  14383. break;
  14384. case Engine.ALPHA_COMBINE:
  14385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14386. this._alphaState.alphaBlend = true;
  14387. break;
  14388. case Engine.ALPHA_ONEONE:
  14389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14390. this._alphaState.alphaBlend = true;
  14391. break;
  14392. case Engine.ALPHA_ADD:
  14393. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14394. this._alphaState.alphaBlend = true;
  14395. break;
  14396. case Engine.ALPHA_SUBTRACT:
  14397. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14398. this._alphaState.alphaBlend = true;
  14399. break;
  14400. case Engine.ALPHA_MULTIPLY:
  14401. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14402. this._alphaState.alphaBlend = true;
  14403. break;
  14404. case Engine.ALPHA_MAXIMIZED:
  14405. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14406. this._alphaState.alphaBlend = true;
  14407. break;
  14408. case Engine.ALPHA_INTERPOLATE:
  14409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14410. this._alphaState.alphaBlend = true;
  14411. break;
  14412. case Engine.ALPHA_SCREENMODE:
  14413. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14414. this._alphaState.alphaBlend = true;
  14415. break;
  14416. }
  14417. if (!noDepthWriteChange) {
  14418. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14419. }
  14420. this._alphaMode = mode;
  14421. };
  14422. /**
  14423. * Gets the current alpha mode
  14424. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14425. * @returns the current alpha mode
  14426. */
  14427. Engine.prototype.getAlphaMode = function () {
  14428. return this._alphaMode;
  14429. };
  14430. // Textures
  14431. /**
  14432. * Clears the list of texture accessible through engine.
  14433. * This can help preventing texture load conflict due to name collision.
  14434. */
  14435. Engine.prototype.clearInternalTexturesCache = function () {
  14436. this._internalTexturesCache = [];
  14437. };
  14438. /**
  14439. * Force the entire cache to be cleared
  14440. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14441. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14442. */
  14443. Engine.prototype.wipeCaches = function (bruteForce) {
  14444. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14445. return;
  14446. }
  14447. this._currentEffect = null;
  14448. this._viewportCached.x = 0;
  14449. this._viewportCached.y = 0;
  14450. this._viewportCached.z = 0;
  14451. this._viewportCached.w = 0;
  14452. if (bruteForce) {
  14453. this.resetTextureCache();
  14454. this._currentProgram = null;
  14455. this._stencilState.reset();
  14456. this._depthCullingState.reset();
  14457. this.setDepthFunctionToLessOrEqual();
  14458. this._alphaState.reset();
  14459. this._unpackFlipYCached = null;
  14460. }
  14461. this._resetVertexBufferBinding();
  14462. this._cachedIndexBuffer = null;
  14463. this._cachedEffectForVertexBuffers = null;
  14464. this._unbindVertexArrayObject();
  14465. this.bindIndexBuffer(null);
  14466. };
  14467. /**
  14468. * Set the compressed texture format to use, based on the formats you have, and the formats
  14469. * supported by the hardware / browser.
  14470. *
  14471. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14472. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14473. * to API arguments needed to compressed textures. This puts the burden on the container
  14474. * generator to house the arcane code for determining these for current & future formats.
  14475. *
  14476. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14477. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14478. *
  14479. * Note: The result of this call is not taken into account when a texture is base64.
  14480. *
  14481. * @param formatsAvailable defines the list of those format families you have created
  14482. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14483. *
  14484. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14485. * @returns The extension selected.
  14486. */
  14487. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14488. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14489. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14490. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14491. return this._textureFormatInUse = this._texturesSupported[i];
  14492. }
  14493. }
  14494. }
  14495. // actively set format to nothing, to allow this to be called more than once
  14496. // and possibly fail the 2nd time
  14497. this._textureFormatInUse = null;
  14498. return null;
  14499. };
  14500. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14501. var gl = this._gl;
  14502. var magFilter = gl.NEAREST;
  14503. var minFilter = gl.NEAREST;
  14504. switch (samplingMode) {
  14505. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14506. magFilter = gl.LINEAR;
  14507. if (generateMipMaps) {
  14508. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14509. }
  14510. else {
  14511. minFilter = gl.LINEAR;
  14512. }
  14513. break;
  14514. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14515. magFilter = gl.LINEAR;
  14516. if (generateMipMaps) {
  14517. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14518. }
  14519. else {
  14520. minFilter = gl.LINEAR;
  14521. }
  14522. break;
  14523. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14524. magFilter = gl.NEAREST;
  14525. if (generateMipMaps) {
  14526. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14527. }
  14528. else {
  14529. minFilter = gl.NEAREST;
  14530. }
  14531. break;
  14532. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14533. magFilter = gl.NEAREST;
  14534. if (generateMipMaps) {
  14535. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14536. }
  14537. else {
  14538. minFilter = gl.NEAREST;
  14539. }
  14540. break;
  14541. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14542. magFilter = gl.NEAREST;
  14543. if (generateMipMaps) {
  14544. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14545. }
  14546. else {
  14547. minFilter = gl.LINEAR;
  14548. }
  14549. break;
  14550. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14551. magFilter = gl.NEAREST;
  14552. if (generateMipMaps) {
  14553. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14554. }
  14555. else {
  14556. minFilter = gl.LINEAR;
  14557. }
  14558. break;
  14559. case Engine.TEXTURE_NEAREST_LINEAR:
  14560. magFilter = gl.NEAREST;
  14561. minFilter = gl.LINEAR;
  14562. break;
  14563. case Engine.TEXTURE_NEAREST_NEAREST:
  14564. magFilter = gl.NEAREST;
  14565. minFilter = gl.NEAREST;
  14566. break;
  14567. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14568. magFilter = gl.LINEAR;
  14569. if (generateMipMaps) {
  14570. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14571. }
  14572. else {
  14573. minFilter = gl.NEAREST;
  14574. }
  14575. break;
  14576. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14577. magFilter = gl.LINEAR;
  14578. if (generateMipMaps) {
  14579. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14580. }
  14581. else {
  14582. minFilter = gl.NEAREST;
  14583. }
  14584. break;
  14585. case Engine.TEXTURE_LINEAR_LINEAR:
  14586. magFilter = gl.LINEAR;
  14587. minFilter = gl.LINEAR;
  14588. break;
  14589. case Engine.TEXTURE_LINEAR_NEAREST:
  14590. magFilter = gl.LINEAR;
  14591. minFilter = gl.NEAREST;
  14592. break;
  14593. }
  14594. return {
  14595. min: minFilter,
  14596. mag: magFilter
  14597. };
  14598. };
  14599. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14600. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14601. var img;
  14602. var onload = function () {
  14603. loadedImages[index] = img;
  14604. loadedImages._internalCount++;
  14605. if (scene) {
  14606. scene._removePendingData(img);
  14607. }
  14608. if (loadedImages._internalCount === 6) {
  14609. onfinish(loadedImages);
  14610. }
  14611. };
  14612. var onerror = function (message, exception) {
  14613. if (scene) {
  14614. scene._removePendingData(img);
  14615. }
  14616. if (onErrorCallBack) {
  14617. onErrorCallBack(message, exception);
  14618. }
  14619. };
  14620. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14621. if (scene) {
  14622. scene._addPendingData(img);
  14623. }
  14624. };
  14625. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14626. if (onError === void 0) { onError = null; }
  14627. var loadedImages = [];
  14628. loadedImages._internalCount = 0;
  14629. for (var index = 0; index < 6; index++) {
  14630. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14631. }
  14632. };
  14633. ;
  14634. /** @hidden */
  14635. Engine.prototype._createTexture = function () {
  14636. var texture = this._gl.createTexture();
  14637. if (!texture) {
  14638. throw new Error("Unable to create texture");
  14639. }
  14640. return texture;
  14641. };
  14642. /**
  14643. * Usually called from BABYLON.Texture.ts.
  14644. * Passed information to create a WebGLTexture
  14645. * @param urlArg defines a value which contains one of the following:
  14646. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14647. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14648. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14649. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14650. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14651. * @param scene needed for loading to the correct scene
  14652. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14653. * @param onLoad optional callback to be called upon successful completion
  14654. * @param onError optional callback to be called upon failure
  14655. * @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
  14656. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14657. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14658. * @param forcedExtension defines the extension to use to pick the right loader
  14659. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14660. */
  14661. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14662. var _this = this;
  14663. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14664. if (onLoad === void 0) { onLoad = null; }
  14665. if (onError === void 0) { onError = null; }
  14666. if (buffer === void 0) { buffer = null; }
  14667. if (fallback === void 0) { fallback = null; }
  14668. if (format === void 0) { format = null; }
  14669. if (forcedExtension === void 0) { forcedExtension = null; }
  14670. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14671. var fromData = url.substr(0, 5) === "data:";
  14672. var fromBlob = url.substr(0, 5) === "blob:";
  14673. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  14674. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14675. // establish the file extension, if possible
  14676. var lastDot = url.lastIndexOf('.');
  14677. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14678. var loader = null;
  14679. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14680. var availableLoader = _a[_i];
  14681. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14682. loader = availableLoader;
  14683. break;
  14684. }
  14685. }
  14686. if (loader) {
  14687. url = loader.transformUrl(url, this._textureFormatInUse);
  14688. }
  14689. if (scene) {
  14690. scene._addPendingData(texture);
  14691. }
  14692. texture.url = url;
  14693. texture.generateMipMaps = !noMipmap;
  14694. texture.samplingMode = samplingMode;
  14695. texture.invertY = invertY;
  14696. if (!this._doNotHandleContextLost) {
  14697. // Keep a link to the buffer only if we plan to handle context lost
  14698. texture._buffer = buffer;
  14699. }
  14700. var onLoadObserver = null;
  14701. if (onLoad && !fallback) {
  14702. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14703. }
  14704. if (!fallback)
  14705. this._internalTexturesCache.push(texture);
  14706. var onInternalError = function (message, exception) {
  14707. if (scene) {
  14708. scene._removePendingData(texture);
  14709. }
  14710. var customFallback = false;
  14711. if (loader) {
  14712. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14713. if (fallbackUrl) {
  14714. // Add Back
  14715. customFallback = true;
  14716. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14717. }
  14718. }
  14719. if (!customFallback) {
  14720. if (onLoadObserver) {
  14721. texture.onLoadedObservable.remove(onLoadObserver);
  14722. }
  14723. if (BABYLON.Tools.UseFallbackTexture) {
  14724. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14725. }
  14726. }
  14727. if (onError) {
  14728. onError(message || "Unknown error", exception);
  14729. }
  14730. };
  14731. // processing for non-image formats
  14732. if (loader) {
  14733. var callback = function (data) {
  14734. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14735. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14736. done();
  14737. return false;
  14738. }, samplingMode);
  14739. });
  14740. };
  14741. if (!buffer) {
  14742. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14743. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14744. });
  14745. }
  14746. else {
  14747. callback(buffer);
  14748. }
  14749. }
  14750. else {
  14751. var onload = function (img) {
  14752. if (fromBlob && !_this._doNotHandleContextLost) {
  14753. // We need to store the image if we need to rebuild the texture
  14754. // in case of a webgl context lost
  14755. texture._buffer = img;
  14756. }
  14757. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14758. var gl = _this._gl;
  14759. var isPot = (img.width === potWidth && img.height === potHeight);
  14760. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14761. if (isPot) {
  14762. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14763. return false;
  14764. }
  14765. var maxTextureSize = _this._caps.maxTextureSize;
  14766. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14767. _this._prepareWorkingCanvas();
  14768. if (!_this._workingCanvas || !_this._workingContext) {
  14769. return false;
  14770. }
  14771. _this._workingCanvas.width = potWidth;
  14772. _this._workingCanvas.height = potHeight;
  14773. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14774. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14775. texture.width = potWidth;
  14776. texture.height = potHeight;
  14777. return false;
  14778. }
  14779. else {
  14780. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14781. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14782. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14783. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14784. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14788. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14789. _this._releaseTexture(source_1);
  14790. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14791. continuationCallback();
  14792. });
  14793. }
  14794. return true;
  14795. }, samplingMode);
  14796. };
  14797. if (!fromData || isBase64) {
  14798. if (buffer instanceof HTMLImageElement) {
  14799. onload(buffer);
  14800. }
  14801. else {
  14802. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14803. }
  14804. }
  14805. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14806. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14807. }
  14808. else {
  14809. onload(buffer);
  14810. }
  14811. }
  14812. return texture;
  14813. };
  14814. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14815. var _this = this;
  14816. var rtt = this.createRenderTargetTexture({
  14817. width: destination.width,
  14818. height: destination.height,
  14819. }, {
  14820. generateMipMaps: false,
  14821. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14822. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14823. generateDepthBuffer: false,
  14824. generateStencilBuffer: false
  14825. });
  14826. if (!this._rescalePostProcess) {
  14827. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14828. }
  14829. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14830. _this._rescalePostProcess.onApply = function (effect) {
  14831. effect._bindTexture("textureSampler", source);
  14832. };
  14833. var hostingScene = scene;
  14834. if (!hostingScene) {
  14835. hostingScene = _this.scenes[_this.scenes.length - 1];
  14836. }
  14837. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14838. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14839. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14840. _this.unBindFramebuffer(rtt);
  14841. _this._releaseTexture(rtt);
  14842. if (onComplete) {
  14843. onComplete();
  14844. }
  14845. });
  14846. };
  14847. /**
  14848. * Update a raw texture
  14849. * @param texture defines the texture to update
  14850. * @param data defines the data to store in the texture
  14851. * @param format defines the format of the data
  14852. * @param invertY defines if data must be stored with Y axis inverted
  14853. * @param compression defines the compression used (null by default)
  14854. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14855. */
  14856. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14857. if (compression === void 0) { compression = null; }
  14858. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14859. if (!texture) {
  14860. return;
  14861. }
  14862. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14863. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14864. // babylon's internalFormat but gl's texImage2D format
  14865. var internalFormat = this._getInternalFormat(format);
  14866. var textureType = this._getWebGLTextureType(type);
  14867. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14868. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14869. if (!this._doNotHandleContextLost) {
  14870. texture._bufferView = data;
  14871. texture.format = format;
  14872. texture.type = type;
  14873. texture.invertY = invertY;
  14874. texture._compression = compression;
  14875. }
  14876. if (texture.width % 4 !== 0) {
  14877. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14878. }
  14879. if (compression && data) {
  14880. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14881. }
  14882. else {
  14883. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14884. }
  14885. if (texture.generateMipMaps) {
  14886. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14887. }
  14888. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14889. // this.resetTextureCache();
  14890. texture.isReady = true;
  14891. };
  14892. /**
  14893. * Creates a raw texture
  14894. * @param data defines the data to store in the texture
  14895. * @param width defines the width of the texture
  14896. * @param height defines the height of the texture
  14897. * @param format defines the format of the data
  14898. * @param generateMipMaps defines if the engine should generate the mip levels
  14899. * @param invertY defines if data must be stored with Y axis inverted
  14900. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14901. * @param compression defines the compression used (null by default)
  14902. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14903. * @returns the raw texture inside an InternalTexture
  14904. */
  14905. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14906. if (compression === void 0) { compression = null; }
  14907. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14908. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14909. texture.baseWidth = width;
  14910. texture.baseHeight = height;
  14911. texture.width = width;
  14912. texture.height = height;
  14913. texture.format = format;
  14914. texture.generateMipMaps = generateMipMaps;
  14915. texture.samplingMode = samplingMode;
  14916. texture.invertY = invertY;
  14917. texture._compression = compression;
  14918. texture.type = type;
  14919. if (!this._doNotHandleContextLost) {
  14920. texture._bufferView = data;
  14921. }
  14922. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14923. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14924. // Filters
  14925. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14927. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14928. if (generateMipMaps) {
  14929. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14930. }
  14931. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14932. this._internalTexturesCache.push(texture);
  14933. return texture;
  14934. };
  14935. /** @hidden */
  14936. Engine.prototype._unpackFlipY = function (value) {
  14937. if (this._unpackFlipYCached !== value) {
  14938. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14939. if (this.enableUnpackFlipYCached) {
  14940. this._unpackFlipYCached = value;
  14941. }
  14942. }
  14943. };
  14944. /** @hidden */
  14945. Engine.prototype._getUnpackAlignement = function () {
  14946. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14947. };
  14948. /**
  14949. * Creates a dynamic texture
  14950. * @param width defines the width of the texture
  14951. * @param height defines the height of the texture
  14952. * @param generateMipMaps defines if the engine should generate the mip levels
  14953. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14954. * @returns the dynamic texture inside an InternalTexture
  14955. */
  14956. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14957. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14958. texture.baseWidth = width;
  14959. texture.baseHeight = height;
  14960. if (generateMipMaps) {
  14961. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14962. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14963. }
  14964. // this.resetTextureCache();
  14965. texture.width = width;
  14966. texture.height = height;
  14967. texture.isReady = false;
  14968. texture.generateMipMaps = generateMipMaps;
  14969. texture.samplingMode = samplingMode;
  14970. this.updateTextureSamplingMode(samplingMode, texture);
  14971. this._internalTexturesCache.push(texture);
  14972. return texture;
  14973. };
  14974. /**
  14975. * Update the sampling mode of a given texture
  14976. * @param samplingMode defines the required sampling mode
  14977. * @param texture defines the texture to update
  14978. */
  14979. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14980. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14981. if (texture.isCube) {
  14982. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14983. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14984. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14985. }
  14986. else if (texture.is3D) {
  14987. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14988. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14989. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14990. }
  14991. else {
  14992. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14993. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14994. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14995. }
  14996. texture.samplingMode = samplingMode;
  14997. };
  14998. /**
  14999. * Update the content of a dynamic texture
  15000. * @param texture defines the texture to update
  15001. * @param canvas defines the canvas containing the source
  15002. * @param invertY defines if data must be stored with Y axis inverted
  15003. * @param premulAlpha defines if alpha is stored as premultiplied
  15004. * @param format defines the format of the data
  15005. */
  15006. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15007. if (premulAlpha === void 0) { premulAlpha = false; }
  15008. if (!texture) {
  15009. return;
  15010. }
  15011. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15012. this._unpackFlipY(invertY);
  15013. if (premulAlpha) {
  15014. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15015. }
  15016. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15017. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15018. if (texture.generateMipMaps) {
  15019. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15020. }
  15021. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15022. if (premulAlpha) {
  15023. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15024. }
  15025. texture.isReady = true;
  15026. };
  15027. /**
  15028. * Update a video texture
  15029. * @param texture defines the texture to update
  15030. * @param video defines the video element to use
  15031. * @param invertY defines if data must be stored with Y axis inverted
  15032. */
  15033. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15034. if (!texture || texture._isDisabled) {
  15035. return;
  15036. }
  15037. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15038. this._unpackFlipY(!invertY); // Video are upside down by default
  15039. try {
  15040. // Testing video texture support
  15041. if (this._videoTextureSupported === undefined) {
  15042. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15043. if (this._gl.getError() !== 0) {
  15044. this._videoTextureSupported = false;
  15045. }
  15046. else {
  15047. this._videoTextureSupported = true;
  15048. }
  15049. }
  15050. // Copy video through the current working canvas if video texture is not supported
  15051. if (!this._videoTextureSupported) {
  15052. if (!texture._workingCanvas) {
  15053. texture._workingCanvas = document.createElement("canvas");
  15054. var context = texture._workingCanvas.getContext("2d");
  15055. if (!context) {
  15056. throw new Error("Unable to get 2d context");
  15057. }
  15058. texture._workingContext = context;
  15059. texture._workingCanvas.width = texture.width;
  15060. texture._workingCanvas.height = texture.height;
  15061. }
  15062. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15063. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15064. }
  15065. else {
  15066. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15067. }
  15068. if (texture.generateMipMaps) {
  15069. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15070. }
  15071. if (!wasPreviouslyBound) {
  15072. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15073. }
  15074. // this.resetTextureCache();
  15075. texture.isReady = true;
  15076. }
  15077. catch (ex) {
  15078. // Something unexpected
  15079. // Let's disable the texture
  15080. texture._isDisabled = true;
  15081. }
  15082. };
  15083. /**
  15084. * Updates a depth texture Comparison Mode and Function.
  15085. * If the comparison Function is equal to 0, the mode will be set to none.
  15086. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15087. * @param texture The texture to set the comparison function for
  15088. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15089. */
  15090. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15091. if (this.webGLVersion === 1) {
  15092. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15093. return;
  15094. }
  15095. var gl = this._gl;
  15096. if (texture.isCube) {
  15097. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15098. if (comparisonFunction === 0) {
  15099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15101. }
  15102. else {
  15103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15104. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15105. }
  15106. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15107. }
  15108. else {
  15109. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15110. if (comparisonFunction === 0) {
  15111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15113. }
  15114. else {
  15115. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15116. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15117. }
  15118. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15119. }
  15120. texture._comparisonFunction = comparisonFunction;
  15121. };
  15122. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15123. var width = size.width || size;
  15124. var height = size.height || size;
  15125. internalTexture.baseWidth = width;
  15126. internalTexture.baseHeight = height;
  15127. internalTexture.width = width;
  15128. internalTexture.height = height;
  15129. internalTexture.isReady = true;
  15130. internalTexture.samples = 1;
  15131. internalTexture.generateMipMaps = false;
  15132. internalTexture._generateDepthBuffer = true;
  15133. internalTexture._generateStencilBuffer = generateStencil;
  15134. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15135. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15136. internalTexture._comparisonFunction = comparisonFunction;
  15137. var gl = this._gl;
  15138. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15139. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15140. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15141. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15142. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15143. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15144. if (comparisonFunction === 0) {
  15145. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15146. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15147. }
  15148. else {
  15149. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15150. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15151. }
  15152. };
  15153. /**
  15154. * Creates a depth stencil texture.
  15155. * This is only available in WebGL 2 or with the depth texture extension available.
  15156. * @param size The size of face edge in the texture.
  15157. * @param options The options defining the texture.
  15158. * @returns The texture
  15159. */
  15160. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15161. if (options.isCube) {
  15162. var width = size.width || size;
  15163. return this._createDepthStencilCubeTexture(width, options);
  15164. }
  15165. else {
  15166. return this._createDepthStencilTexture(size, options);
  15167. }
  15168. };
  15169. /**
  15170. * Creates a depth stencil texture.
  15171. * This is only available in WebGL 2 or with the depth texture extension available.
  15172. * @param size The size of face edge in the texture.
  15173. * @param options The options defining the texture.
  15174. * @returns The texture
  15175. */
  15176. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15177. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15178. if (!this._caps.depthTextureExtension) {
  15179. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15180. return internalTexture;
  15181. }
  15182. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15183. var gl = this._gl;
  15184. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15185. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15186. if (this.webGLVersion > 1) {
  15187. if (internalOptions.generateStencil) {
  15188. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15189. }
  15190. else {
  15191. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15192. }
  15193. }
  15194. else {
  15195. if (internalOptions.generateStencil) {
  15196. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15197. }
  15198. else {
  15199. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15200. }
  15201. }
  15202. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15203. return internalTexture;
  15204. };
  15205. /**
  15206. * Creates a depth stencil cube texture.
  15207. * This is only available in WebGL 2.
  15208. * @param size The size of face edge in the cube texture.
  15209. * @param options The options defining the cube texture.
  15210. * @returns The cube texture
  15211. */
  15212. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15213. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15214. internalTexture.isCube = true;
  15215. if (this.webGLVersion === 1) {
  15216. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15217. return internalTexture;
  15218. }
  15219. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15220. var gl = this._gl;
  15221. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15222. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15223. // Create the depth/stencil buffer
  15224. for (var face = 0; face < 6; face++) {
  15225. if (internalOptions.generateStencil) {
  15226. 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);
  15227. }
  15228. else {
  15229. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15230. }
  15231. }
  15232. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15233. return internalTexture;
  15234. };
  15235. /**
  15236. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15237. * @param renderTarget The render target to set the frame buffer for
  15238. */
  15239. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15240. // Create the framebuffer
  15241. var internalTexture = renderTarget.getInternalTexture();
  15242. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15243. return;
  15244. }
  15245. var gl = this._gl;
  15246. var depthStencilTexture = renderTarget.depthStencilTexture;
  15247. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15248. if (depthStencilTexture.isCube) {
  15249. if (depthStencilTexture._generateStencilBuffer) {
  15250. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15251. }
  15252. else {
  15253. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15254. }
  15255. }
  15256. else {
  15257. if (depthStencilTexture._generateStencilBuffer) {
  15258. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15259. }
  15260. else {
  15261. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15262. }
  15263. }
  15264. this.bindUnboundFramebuffer(null);
  15265. };
  15266. /**
  15267. * Creates a new render target texture
  15268. * @param size defines the size of the texture
  15269. * @param options defines the options used to create the texture
  15270. * @returns a new render target texture stored in an InternalTexture
  15271. */
  15272. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15273. var fullOptions = new RenderTargetCreationOptions();
  15274. if (options !== undefined && typeof options === "object") {
  15275. fullOptions.generateMipMaps = options.generateMipMaps;
  15276. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15277. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15278. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15279. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15280. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15281. }
  15282. else {
  15283. fullOptions.generateMipMaps = options;
  15284. fullOptions.generateDepthBuffer = true;
  15285. fullOptions.generateStencilBuffer = false;
  15286. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15287. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15288. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15289. }
  15290. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15291. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15292. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15293. }
  15294. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15295. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15296. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15297. }
  15298. var gl = this._gl;
  15299. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15300. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15301. var width = size.width || size;
  15302. var height = size.height || size;
  15303. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15304. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15305. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15306. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15307. }
  15308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15312. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15313. // Create the framebuffer
  15314. var currentFrameBuffer = this._currentFramebuffer;
  15315. var framebuffer = gl.createFramebuffer();
  15316. this.bindUnboundFramebuffer(framebuffer);
  15317. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15318. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15319. if (fullOptions.generateMipMaps) {
  15320. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15321. }
  15322. // Unbind
  15323. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15324. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15325. this.bindUnboundFramebuffer(currentFrameBuffer);
  15326. texture._framebuffer = framebuffer;
  15327. texture.baseWidth = width;
  15328. texture.baseHeight = height;
  15329. texture.width = width;
  15330. texture.height = height;
  15331. texture.isReady = true;
  15332. texture.samples = 1;
  15333. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15334. texture.samplingMode = fullOptions.samplingMode;
  15335. texture.type = fullOptions.type;
  15336. texture.format = fullOptions.format;
  15337. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15338. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15339. // this.resetTextureCache();
  15340. this._internalTexturesCache.push(texture);
  15341. return texture;
  15342. };
  15343. /**
  15344. * Create a multi render target texture
  15345. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15346. * @param size defines the size of the texture
  15347. * @param options defines the creation options
  15348. * @returns the cube texture as an InternalTexture
  15349. */
  15350. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15351. var generateMipMaps = false;
  15352. var generateDepthBuffer = true;
  15353. var generateStencilBuffer = false;
  15354. var generateDepthTexture = false;
  15355. var textureCount = 1;
  15356. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15357. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15358. var types = new Array();
  15359. var samplingModes = new Array();
  15360. if (options !== undefined) {
  15361. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15362. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15363. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15364. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15365. textureCount = options.textureCount || 1;
  15366. if (options.types) {
  15367. types = options.types;
  15368. }
  15369. if (options.samplingModes) {
  15370. samplingModes = options.samplingModes;
  15371. }
  15372. }
  15373. var gl = this._gl;
  15374. // Create the framebuffer
  15375. var framebuffer = gl.createFramebuffer();
  15376. this.bindUnboundFramebuffer(framebuffer);
  15377. var width = size.width || size;
  15378. var height = size.height || size;
  15379. var textures = [];
  15380. var attachments = [];
  15381. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15382. for (var i = 0; i < textureCount; i++) {
  15383. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15384. var type = types[i] || defaultType;
  15385. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15386. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15387. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15388. }
  15389. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15390. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15391. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15392. }
  15393. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15394. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15395. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15396. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15397. }
  15398. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15399. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15400. textures.push(texture);
  15401. attachments.push(attachment);
  15402. gl.activeTexture(gl["TEXTURE" + i]);
  15403. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15404. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15405. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15406. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15407. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15408. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15409. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15410. if (generateMipMaps) {
  15411. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15412. }
  15413. // Unbind
  15414. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15415. texture._framebuffer = framebuffer;
  15416. texture._depthStencilBuffer = depthStencilBuffer;
  15417. texture.baseWidth = width;
  15418. texture.baseHeight = height;
  15419. texture.width = width;
  15420. texture.height = height;
  15421. texture.isReady = true;
  15422. texture.samples = 1;
  15423. texture.generateMipMaps = generateMipMaps;
  15424. texture.samplingMode = samplingMode;
  15425. texture.type = type;
  15426. texture._generateDepthBuffer = generateDepthBuffer;
  15427. texture._generateStencilBuffer = generateStencilBuffer;
  15428. texture._attachments = attachments;
  15429. this._internalTexturesCache.push(texture);
  15430. }
  15431. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15432. // Depth texture
  15433. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15434. gl.activeTexture(gl.TEXTURE0);
  15435. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15440. 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);
  15441. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15442. depthTexture._framebuffer = framebuffer;
  15443. depthTexture.baseWidth = width;
  15444. depthTexture.baseHeight = height;
  15445. depthTexture.width = width;
  15446. depthTexture.height = height;
  15447. depthTexture.isReady = true;
  15448. depthTexture.samples = 1;
  15449. depthTexture.generateMipMaps = generateMipMaps;
  15450. depthTexture.samplingMode = gl.NEAREST;
  15451. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15452. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15453. textures.push(depthTexture);
  15454. this._internalTexturesCache.push(depthTexture);
  15455. }
  15456. gl.drawBuffers(attachments);
  15457. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15458. this.bindUnboundFramebuffer(null);
  15459. this.resetTextureCache();
  15460. return textures;
  15461. };
  15462. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15463. if (samples === void 0) { samples = 1; }
  15464. var depthStencilBuffer = null;
  15465. var gl = this._gl;
  15466. // Create the depth/stencil buffer
  15467. if (generateStencilBuffer) {
  15468. depthStencilBuffer = gl.createRenderbuffer();
  15469. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15470. if (samples > 1) {
  15471. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15472. }
  15473. else {
  15474. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15475. }
  15476. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15477. }
  15478. else if (generateDepthBuffer) {
  15479. depthStencilBuffer = gl.createRenderbuffer();
  15480. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15481. if (samples > 1) {
  15482. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15483. }
  15484. else {
  15485. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15486. }
  15487. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15488. }
  15489. return depthStencilBuffer;
  15490. };
  15491. /**
  15492. * Updates the sample count of a render target texture
  15493. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15494. * @param texture defines the texture to update
  15495. * @param samples defines the sample count to set
  15496. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15497. */
  15498. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15499. if (this.webGLVersion < 2 || !texture) {
  15500. return 1;
  15501. }
  15502. if (texture.samples === samples) {
  15503. return samples;
  15504. }
  15505. var gl = this._gl;
  15506. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15507. // Dispose previous render buffers
  15508. if (texture._depthStencilBuffer) {
  15509. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15510. texture._depthStencilBuffer = null;
  15511. }
  15512. if (texture._MSAAFramebuffer) {
  15513. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15514. texture._MSAAFramebuffer = null;
  15515. }
  15516. if (texture._MSAARenderBuffer) {
  15517. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15518. texture._MSAARenderBuffer = null;
  15519. }
  15520. if (samples > 1) {
  15521. var framebuffer = gl.createFramebuffer();
  15522. if (!framebuffer) {
  15523. throw new Error("Unable to create multi sampled framebuffer");
  15524. }
  15525. texture._MSAAFramebuffer = framebuffer;
  15526. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15527. var colorRenderbuffer = gl.createRenderbuffer();
  15528. if (!colorRenderbuffer) {
  15529. throw new Error("Unable to create multi sampled framebuffer");
  15530. }
  15531. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15532. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15533. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15534. texture._MSAARenderBuffer = colorRenderbuffer;
  15535. }
  15536. else {
  15537. this.bindUnboundFramebuffer(texture._framebuffer);
  15538. }
  15539. texture.samples = samples;
  15540. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15541. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15542. this.bindUnboundFramebuffer(null);
  15543. return samples;
  15544. };
  15545. /**
  15546. * Update the sample count for a given multiple render target texture
  15547. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15548. * @param textures defines the textures to update
  15549. * @param samples defines the sample count to set
  15550. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15551. */
  15552. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15553. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15554. return 1;
  15555. }
  15556. if (textures[0].samples === samples) {
  15557. return samples;
  15558. }
  15559. var gl = this._gl;
  15560. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15561. // Dispose previous render buffers
  15562. if (textures[0]._depthStencilBuffer) {
  15563. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15564. textures[0]._depthStencilBuffer = null;
  15565. }
  15566. if (textures[0]._MSAAFramebuffer) {
  15567. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15568. textures[0]._MSAAFramebuffer = null;
  15569. }
  15570. for (var i = 0; i < textures.length; i++) {
  15571. if (textures[i]._MSAARenderBuffer) {
  15572. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15573. textures[i]._MSAARenderBuffer = null;
  15574. }
  15575. }
  15576. if (samples > 1) {
  15577. var framebuffer = gl.createFramebuffer();
  15578. if (!framebuffer) {
  15579. throw new Error("Unable to create multi sampled framebuffer");
  15580. }
  15581. this.bindUnboundFramebuffer(framebuffer);
  15582. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15583. var attachments = [];
  15584. for (var i = 0; i < textures.length; i++) {
  15585. var texture = textures[i];
  15586. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15587. var colorRenderbuffer = gl.createRenderbuffer();
  15588. if (!colorRenderbuffer) {
  15589. throw new Error("Unable to create multi sampled framebuffer");
  15590. }
  15591. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15592. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15593. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15594. texture._MSAAFramebuffer = framebuffer;
  15595. texture._MSAARenderBuffer = colorRenderbuffer;
  15596. texture.samples = samples;
  15597. texture._depthStencilBuffer = depthStencilBuffer;
  15598. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15599. attachments.push(attachment);
  15600. }
  15601. gl.drawBuffers(attachments);
  15602. }
  15603. else {
  15604. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15605. }
  15606. this.bindUnboundFramebuffer(null);
  15607. return samples;
  15608. };
  15609. /** @hidden */
  15610. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15611. if (faceIndex === void 0) { faceIndex = 0; }
  15612. if (lod === void 0) { lod = 0; }
  15613. var gl = this._gl;
  15614. var target = gl.TEXTURE_2D;
  15615. if (texture.isCube) {
  15616. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15617. }
  15618. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15619. };
  15620. /** @hidden */
  15621. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15622. if (faceIndex === void 0) { faceIndex = 0; }
  15623. if (lod === void 0) { lod = 0; }
  15624. var gl = this._gl;
  15625. var textureType = this._getWebGLTextureType(texture.type);
  15626. var format = this._getInternalFormat(texture.format);
  15627. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15628. this._unpackFlipY(texture.invertY);
  15629. var target = gl.TEXTURE_2D;
  15630. if (texture.isCube) {
  15631. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15632. }
  15633. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15634. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15635. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15636. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15637. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15638. };
  15639. /** @hidden */
  15640. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15641. if (faceIndex === void 0) { faceIndex = 0; }
  15642. if (lod === void 0) { lod = 0; }
  15643. var gl = this._gl;
  15644. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15645. this._bindTextureDirectly(bindTarget, texture, true);
  15646. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15647. this._bindTextureDirectly(bindTarget, null, true);
  15648. };
  15649. /** @hidden */
  15650. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15651. if (faceIndex === void 0) { faceIndex = 0; }
  15652. if (lod === void 0) { lod = 0; }
  15653. var gl = this._gl;
  15654. var textureType = this._getWebGLTextureType(texture.type);
  15655. var format = this._getInternalFormat(texture.format);
  15656. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15657. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15658. this._bindTextureDirectly(bindTarget, texture, true);
  15659. this._unpackFlipY(texture.invertY);
  15660. var target = gl.TEXTURE_2D;
  15661. if (texture.isCube) {
  15662. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15663. }
  15664. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15665. this._bindTextureDirectly(bindTarget, null, true);
  15666. };
  15667. /**
  15668. * Creates a new render target cube texture
  15669. * @param size defines the size of the texture
  15670. * @param options defines the options used to create the texture
  15671. * @returns a new render target cube texture stored in an InternalTexture
  15672. */
  15673. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15674. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15675. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15676. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15677. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15678. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15679. }
  15680. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15681. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15682. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15683. }
  15684. var gl = this._gl;
  15685. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15686. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15687. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15688. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15689. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15690. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15691. }
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15696. for (var face = 0; face < 6; face++) {
  15697. 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);
  15698. }
  15699. // Create the framebuffer
  15700. var framebuffer = gl.createFramebuffer();
  15701. this.bindUnboundFramebuffer(framebuffer);
  15702. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15703. // MipMaps
  15704. if (fullOptions.generateMipMaps) {
  15705. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15706. }
  15707. // Unbind
  15708. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15709. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15710. this.bindUnboundFramebuffer(null);
  15711. texture._framebuffer = framebuffer;
  15712. texture.width = size;
  15713. texture.height = size;
  15714. texture.isReady = true;
  15715. texture.isCube = true;
  15716. texture.samples = 1;
  15717. texture.generateMipMaps = fullOptions.generateMipMaps;
  15718. texture.samplingMode = fullOptions.samplingMode;
  15719. texture.type = fullOptions.type;
  15720. texture.format = fullOptions.format;
  15721. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15722. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15723. this._internalTexturesCache.push(texture);
  15724. return texture;
  15725. };
  15726. /**
  15727. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15728. * @param rootUrl defines the url where the file to load is located
  15729. * @param scene defines the current scene
  15730. * @param lodScale defines scale to apply to the mip map selection
  15731. * @param lodOffset defines offset to apply to the mip map selection
  15732. * @param onLoad defines an optional callback raised when the texture is loaded
  15733. * @param onError defines an optional callback raised if there is an issue to load the texture
  15734. * @param format defines the format of the data
  15735. * @param forcedExtension defines the extension to use to pick the right loader
  15736. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15737. * @returns the cube texture as an InternalTexture
  15738. */
  15739. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15740. var _this = this;
  15741. if (onLoad === void 0) { onLoad = null; }
  15742. if (onError === void 0) { onError = null; }
  15743. if (forcedExtension === void 0) { forcedExtension = null; }
  15744. if (createPolynomials === void 0) { createPolynomials = true; }
  15745. var callback = function (loadData) {
  15746. if (!loadData) {
  15747. if (onLoad) {
  15748. onLoad(null);
  15749. }
  15750. return;
  15751. }
  15752. var texture = loadData.texture;
  15753. if (!createPolynomials) {
  15754. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15755. }
  15756. else if (loadData.info.sphericalPolynomial) {
  15757. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15758. }
  15759. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15760. if (_this._caps.textureLOD) {
  15761. // Do not add extra process if texture lod is supported.
  15762. if (onLoad) {
  15763. onLoad(texture);
  15764. }
  15765. return;
  15766. }
  15767. var mipSlices = 3;
  15768. var gl = _this._gl;
  15769. var width = loadData.width;
  15770. if (!width) {
  15771. return;
  15772. }
  15773. var textures = [];
  15774. for (var i = 0; i < mipSlices; i++) {
  15775. //compute LOD from even spacing in smoothness (matching shader calculation)
  15776. var smoothness = i / (mipSlices - 1);
  15777. var roughness = 1 - smoothness;
  15778. var minLODIndex = lodOffset; // roughness = 0
  15779. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15780. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15781. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15782. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15783. glTextureFromLod.type = texture.type;
  15784. glTextureFromLod.format = texture.format;
  15785. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15786. glTextureFromLod.height = glTextureFromLod.width;
  15787. glTextureFromLod.isCube = true;
  15788. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15793. if (loadData.isDDS) {
  15794. var info = loadData.info;
  15795. var data = loadData.data;
  15796. _this._unpackFlipY(info.isCompressed);
  15797. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15798. }
  15799. else {
  15800. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15801. }
  15802. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15803. // Wrap in a base texture for easy binding.
  15804. var lodTexture = new BABYLON.BaseTexture(scene);
  15805. lodTexture.isCube = true;
  15806. lodTexture._texture = glTextureFromLod;
  15807. glTextureFromLod.isReady = true;
  15808. textures.push(lodTexture);
  15809. }
  15810. texture._lodTextureHigh = textures[2];
  15811. texture._lodTextureMid = textures[1];
  15812. texture._lodTextureLow = textures[0];
  15813. if (onLoad) {
  15814. onLoad(texture);
  15815. }
  15816. };
  15817. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15818. };
  15819. /**
  15820. * Creates a cube texture
  15821. * @param rootUrl defines the url where the files to load is located
  15822. * @param scene defines the current scene
  15823. * @param files defines the list of files to load (1 per face)
  15824. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15825. * @param onLoad defines an optional callback raised when the texture is loaded
  15826. * @param onError defines an optional callback raised if there is an issue to load the texture
  15827. * @param format defines the format of the data
  15828. * @param forcedExtension defines the extension to use to pick the right loader
  15829. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15830. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15831. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15832. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15833. * @returns the cube texture as an InternalTexture
  15834. */
  15835. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15836. var _this = this;
  15837. if (onLoad === void 0) { onLoad = null; }
  15838. if (onError === void 0) { onError = null; }
  15839. if (forcedExtension === void 0) { forcedExtension = null; }
  15840. if (createPolynomials === void 0) { createPolynomials = false; }
  15841. if (lodScale === void 0) { lodScale = 0; }
  15842. if (lodOffset === void 0) { lodOffset = 0; }
  15843. if (fallback === void 0) { fallback = null; }
  15844. var gl = this._gl;
  15845. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15846. texture.isCube = true;
  15847. texture.url = rootUrl;
  15848. texture.generateMipMaps = !noMipmap;
  15849. texture._lodGenerationScale = lodScale;
  15850. texture._lodGenerationOffset = lodOffset;
  15851. if (!this._doNotHandleContextLost) {
  15852. texture._extension = forcedExtension;
  15853. texture._files = files;
  15854. }
  15855. var lastDot = rootUrl.lastIndexOf('.');
  15856. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15857. var loader = null;
  15858. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15859. var availableLoader = _a[_i];
  15860. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15861. loader = availableLoader;
  15862. break;
  15863. }
  15864. }
  15865. var onInternalError = function (request, exception) {
  15866. if (loader) {
  15867. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15868. if (fallbackUrl) {
  15869. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15870. }
  15871. }
  15872. if (onError && request) {
  15873. onError(request.status + " " + request.statusText, exception);
  15874. }
  15875. };
  15876. if (loader) {
  15877. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15878. var onloaddata = function (data) {
  15879. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15880. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15881. };
  15882. if (files && files.length === 6) {
  15883. if (loader.supportCascades) {
  15884. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15885. }
  15886. else if (onError) {
  15887. onError("Textures type does not support cascades.");
  15888. }
  15889. }
  15890. else {
  15891. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15892. }
  15893. }
  15894. else {
  15895. if (!files) {
  15896. throw new Error("Cannot load cubemap because files were not defined");
  15897. }
  15898. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15899. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15900. var height = width;
  15901. _this._prepareWorkingCanvas();
  15902. if (!_this._workingCanvas || !_this._workingContext) {
  15903. return;
  15904. }
  15905. _this._workingCanvas.width = width;
  15906. _this._workingCanvas.height = height;
  15907. var faces = [
  15908. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15909. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15910. ];
  15911. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15912. _this._unpackFlipY(false);
  15913. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15914. for (var index = 0; index < faces.length; index++) {
  15915. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15916. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15917. }
  15918. if (!noMipmap) {
  15919. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15920. }
  15921. _this._setCubeMapTextureParams(!noMipmap);
  15922. texture.width = width;
  15923. texture.height = height;
  15924. texture.isReady = true;
  15925. if (format) {
  15926. texture.format = format;
  15927. }
  15928. texture.onLoadedObservable.notifyObservers(texture);
  15929. texture.onLoadedObservable.clear();
  15930. if (onLoad) {
  15931. onLoad();
  15932. }
  15933. }, files, onError);
  15934. }
  15935. this._internalTexturesCache.push(texture);
  15936. return texture;
  15937. };
  15938. /**
  15939. * @hidden
  15940. */
  15941. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15942. var gl = this._gl;
  15943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15946. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15947. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15948. // this.resetTextureCache();
  15949. };
  15950. /**
  15951. * Update a raw cube texture
  15952. * @param texture defines the texture to udpdate
  15953. * @param data defines the data to store
  15954. * @param format defines the data format
  15955. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15956. * @param invertY defines if data must be stored with Y axis inverted
  15957. * @param compression defines the compression used (null by default)
  15958. * @param level defines which level of the texture to update
  15959. */
  15960. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15961. if (compression === void 0) { compression = null; }
  15962. if (level === void 0) { level = 0; }
  15963. texture._bufferViewArray = data;
  15964. texture.format = format;
  15965. texture.type = type;
  15966. texture.invertY = invertY;
  15967. texture._compression = compression;
  15968. var gl = this._gl;
  15969. var textureType = this._getWebGLTextureType(type);
  15970. var internalFormat = this._getInternalFormat(format);
  15971. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15972. var needConversion = false;
  15973. if (internalFormat === gl.RGB) {
  15974. internalFormat = gl.RGBA;
  15975. needConversion = true;
  15976. }
  15977. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15978. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15979. if (texture.width % 4 !== 0) {
  15980. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15981. }
  15982. // Data are known to be in +X +Y +Z -X -Y -Z
  15983. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15984. var faceData = data[faceIndex];
  15985. if (compression) {
  15986. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15987. }
  15988. else {
  15989. if (needConversion) {
  15990. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15991. }
  15992. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15993. }
  15994. }
  15995. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15996. if (isPot && texture.generateMipMaps && level === 0) {
  15997. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15998. }
  15999. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16000. // this.resetTextureCache();
  16001. texture.isReady = true;
  16002. };
  16003. /**
  16004. * Creates a new raw cube texture
  16005. * @param data defines the array of data to use to create each face
  16006. * @param size defines the size of the textures
  16007. * @param format defines the format of the data
  16008. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16009. * @param generateMipMaps defines if the engine should generate the mip levels
  16010. * @param invertY defines if data must be stored with Y axis inverted
  16011. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16012. * @param compression defines the compression used (null by default)
  16013. * @returns the cube texture as an InternalTexture
  16014. */
  16015. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16016. if (compression === void 0) { compression = null; }
  16017. var gl = this._gl;
  16018. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16019. texture.isCube = true;
  16020. texture.format = format;
  16021. texture.type = type;
  16022. if (!this._doNotHandleContextLost) {
  16023. texture._bufferViewArray = data;
  16024. }
  16025. var textureType = this._getWebGLTextureType(type);
  16026. var internalFormat = this._getInternalFormat(format);
  16027. if (internalFormat === gl.RGB) {
  16028. internalFormat = gl.RGBA;
  16029. }
  16030. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16031. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16032. generateMipMaps = false;
  16033. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16034. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16035. }
  16036. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16037. generateMipMaps = false;
  16038. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16039. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16040. }
  16041. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16042. generateMipMaps = false;
  16043. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16044. }
  16045. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16046. generateMipMaps = false;
  16047. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16048. }
  16049. var width = size;
  16050. var height = width;
  16051. texture.width = width;
  16052. texture.height = height;
  16053. // Double check on POT to generate Mips.
  16054. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16055. if (!isPot) {
  16056. generateMipMaps = false;
  16057. }
  16058. // Upload data if needed. The texture won't be ready until then.
  16059. if (data) {
  16060. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16061. }
  16062. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16063. // Filters
  16064. if (data && generateMipMaps) {
  16065. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16066. }
  16067. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16072. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16073. texture.generateMipMaps = generateMipMaps;
  16074. return texture;
  16075. };
  16076. /**
  16077. * Creates a new raw cube texture from a specified url
  16078. * @param url defines the url where the data is located
  16079. * @param scene defines the current scene
  16080. * @param size defines the size of the textures
  16081. * @param format defines the format of the data
  16082. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16083. * @param noMipmap defines if the engine should avoid generating the mip levels
  16084. * @param callback defines a callback used to extract texture data from loaded data
  16085. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16086. * @param onLoad defines a callback called when texture is loaded
  16087. * @param onError defines a callback called if there is an error
  16088. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16089. * @param invertY defines if data must be stored with Y axis inverted
  16090. * @returns the cube texture as an InternalTexture
  16091. */
  16092. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16093. var _this = this;
  16094. if (onLoad === void 0) { onLoad = null; }
  16095. if (onError === void 0) { onError = null; }
  16096. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16097. if (invertY === void 0) { invertY = false; }
  16098. var gl = this._gl;
  16099. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16100. scene._addPendingData(texture);
  16101. texture.url = url;
  16102. this._internalTexturesCache.push(texture);
  16103. var onerror = function (request, exception) {
  16104. scene._removePendingData(texture);
  16105. if (onError && request) {
  16106. onError(request.status + " " + request.statusText, exception);
  16107. }
  16108. };
  16109. var internalCallback = function (data) {
  16110. var width = texture.width;
  16111. var faceDataArrays = callback(data);
  16112. if (!faceDataArrays) {
  16113. return;
  16114. }
  16115. if (mipmapGenerator) {
  16116. var textureType = _this._getWebGLTextureType(type);
  16117. var internalFormat = _this._getInternalFormat(format);
  16118. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16119. var needConversion = false;
  16120. if (internalFormat === gl.RGB) {
  16121. internalFormat = gl.RGBA;
  16122. needConversion = true;
  16123. }
  16124. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16125. _this._unpackFlipY(false);
  16126. var mipData = mipmapGenerator(faceDataArrays);
  16127. for (var level = 0; level < mipData.length; level++) {
  16128. var mipSize = width >> level;
  16129. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16130. var mipFaceData = mipData[level][faceIndex];
  16131. if (needConversion) {
  16132. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16133. }
  16134. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16135. }
  16136. }
  16137. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16138. }
  16139. else {
  16140. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16141. }
  16142. texture.isReady = true;
  16143. // this.resetTextureCache();
  16144. scene._removePendingData(texture);
  16145. if (onLoad) {
  16146. onLoad();
  16147. }
  16148. };
  16149. this._loadFile(url, function (data) {
  16150. internalCallback(data);
  16151. }, undefined, scene.database, true, onerror);
  16152. return texture;
  16153. };
  16154. ;
  16155. /**
  16156. * Update a raw 3D texture
  16157. * @param texture defines the texture to update
  16158. * @param data defines the data to store
  16159. * @param format defines the data format
  16160. * @param invertY defines if data must be stored with Y axis inverted
  16161. * @param compression defines the used compression (can be null)
  16162. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16163. */
  16164. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16165. if (compression === void 0) { compression = null; }
  16166. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16167. var internalType = this._getWebGLTextureType(textureType);
  16168. var internalFormat = this._getInternalFormat(format);
  16169. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16170. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16171. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16172. if (!this._doNotHandleContextLost) {
  16173. texture._bufferView = data;
  16174. texture.format = format;
  16175. texture.invertY = invertY;
  16176. texture._compression = compression;
  16177. }
  16178. if (texture.width % 4 !== 0) {
  16179. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16180. }
  16181. if (compression && data) {
  16182. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16183. }
  16184. else {
  16185. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16186. }
  16187. if (texture.generateMipMaps) {
  16188. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16189. }
  16190. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16191. // this.resetTextureCache();
  16192. texture.isReady = true;
  16193. };
  16194. /**
  16195. * Creates a new raw 3D texture
  16196. * @param data defines the data used to create the texture
  16197. * @param width defines the width of the texture
  16198. * @param height defines the height of the texture
  16199. * @param depth defines the depth of the texture
  16200. * @param format defines the format of the texture
  16201. * @param generateMipMaps defines if the engine must generate mip levels
  16202. * @param invertY defines if data must be stored with Y axis inverted
  16203. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16204. * @param compression defines the compressed used (can be null)
  16205. * @param textureType defines the compressed used (can be null)
  16206. * @returns a new raw 3D texture (stored in an InternalTexture)
  16207. */
  16208. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16209. if (compression === void 0) { compression = null; }
  16210. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16211. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16212. texture.baseWidth = width;
  16213. texture.baseHeight = height;
  16214. texture.baseDepth = depth;
  16215. texture.width = width;
  16216. texture.height = height;
  16217. texture.depth = depth;
  16218. texture.format = format;
  16219. texture.type = textureType;
  16220. texture.generateMipMaps = generateMipMaps;
  16221. texture.samplingMode = samplingMode;
  16222. texture.is3D = true;
  16223. if (!this._doNotHandleContextLost) {
  16224. texture._bufferView = data;
  16225. }
  16226. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16227. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16228. // Filters
  16229. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16230. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16231. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16232. if (generateMipMaps) {
  16233. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16234. }
  16235. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16236. this._internalTexturesCache.push(texture);
  16237. return texture;
  16238. };
  16239. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16240. var gl = this._gl;
  16241. if (!gl) {
  16242. return;
  16243. }
  16244. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16245. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16247. if (!noMipmap && !isCompressed) {
  16248. gl.generateMipmap(gl.TEXTURE_2D);
  16249. }
  16250. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16251. // this.resetTextureCache();
  16252. if (scene) {
  16253. scene._removePendingData(texture);
  16254. }
  16255. texture.onLoadedObservable.notifyObservers(texture);
  16256. texture.onLoadedObservable.clear();
  16257. };
  16258. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16259. var _this = this;
  16260. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16261. var maxTextureSize = this.getCaps().maxTextureSize;
  16262. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16263. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16264. var gl = this._gl;
  16265. if (!gl) {
  16266. return;
  16267. }
  16268. if (!texture._webGLTexture) {
  16269. // this.resetTextureCache();
  16270. if (scene) {
  16271. scene._removePendingData(texture);
  16272. }
  16273. return;
  16274. }
  16275. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16276. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16277. texture.baseWidth = width;
  16278. texture.baseHeight = height;
  16279. texture.width = potWidth;
  16280. texture.height = potHeight;
  16281. texture.isReady = true;
  16282. if (processFunction(potWidth, potHeight, function () {
  16283. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16284. })) {
  16285. // Returning as texture needs extra async steps
  16286. return;
  16287. }
  16288. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16289. };
  16290. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16291. // Create new RGBA data container.
  16292. var rgbaData;
  16293. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16294. rgbaData = new Float32Array(width * height * 4);
  16295. }
  16296. else {
  16297. rgbaData = new Uint32Array(width * height * 4);
  16298. }
  16299. // Convert each pixel.
  16300. for (var x = 0; x < width; x++) {
  16301. for (var y = 0; y < height; y++) {
  16302. var index = (y * width + x) * 3;
  16303. var newIndex = (y * width + x) * 4;
  16304. // Map Old Value to new value.
  16305. rgbaData[newIndex + 0] = rgbData[index + 0];
  16306. rgbaData[newIndex + 1] = rgbData[index + 1];
  16307. rgbaData[newIndex + 2] = rgbData[index + 2];
  16308. // Add fully opaque alpha channel.
  16309. rgbaData[newIndex + 3] = 1;
  16310. }
  16311. }
  16312. return rgbaData;
  16313. };
  16314. /** @hidden */
  16315. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16316. var gl = this._gl;
  16317. if (texture._framebuffer) {
  16318. gl.deleteFramebuffer(texture._framebuffer);
  16319. texture._framebuffer = null;
  16320. }
  16321. if (texture._depthStencilBuffer) {
  16322. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16323. texture._depthStencilBuffer = null;
  16324. }
  16325. if (texture._MSAAFramebuffer) {
  16326. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16327. texture._MSAAFramebuffer = null;
  16328. }
  16329. if (texture._MSAARenderBuffer) {
  16330. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16331. texture._MSAARenderBuffer = null;
  16332. }
  16333. };
  16334. /** @hidden */
  16335. Engine.prototype._releaseTexture = function (texture) {
  16336. var gl = this._gl;
  16337. this._releaseFramebufferObjects(texture);
  16338. gl.deleteTexture(texture._webGLTexture);
  16339. // Unbind channels
  16340. this.unbindAllTextures();
  16341. var index = this._internalTexturesCache.indexOf(texture);
  16342. if (index !== -1) {
  16343. this._internalTexturesCache.splice(index, 1);
  16344. }
  16345. // Integrated fixed lod samplers.
  16346. if (texture._lodTextureHigh) {
  16347. texture._lodTextureHigh.dispose();
  16348. }
  16349. if (texture._lodTextureMid) {
  16350. texture._lodTextureMid.dispose();
  16351. }
  16352. if (texture._lodTextureLow) {
  16353. texture._lodTextureLow.dispose();
  16354. }
  16355. // Set output texture of post process to null if the texture has been released/disposed
  16356. this.scenes.forEach(function (scene) {
  16357. scene.postProcesses.forEach(function (postProcess) {
  16358. if (postProcess._outputTexture == texture) {
  16359. postProcess._outputTexture = null;
  16360. }
  16361. });
  16362. scene.cameras.forEach(function (camera) {
  16363. camera._postProcesses.forEach(function (postProcess) {
  16364. if (postProcess) {
  16365. if (postProcess._outputTexture == texture) {
  16366. postProcess._outputTexture = null;
  16367. }
  16368. }
  16369. });
  16370. });
  16371. });
  16372. };
  16373. Engine.prototype.setProgram = function (program) {
  16374. if (this._currentProgram !== program) {
  16375. this._gl.useProgram(program);
  16376. this._currentProgram = program;
  16377. }
  16378. };
  16379. /**
  16380. * Binds an effect to the webGL context
  16381. * @param effect defines the effect to bind
  16382. */
  16383. Engine.prototype.bindSamplers = function (effect) {
  16384. this.setProgram(effect.getProgram());
  16385. var samplers = effect.getSamplers();
  16386. for (var index = 0; index < samplers.length; index++) {
  16387. var uniform = effect.getUniform(samplers[index]);
  16388. if (uniform) {
  16389. this._boundUniforms[index] = uniform;
  16390. }
  16391. }
  16392. this._currentEffect = null;
  16393. };
  16394. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16395. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16396. return;
  16397. }
  16398. // Remove
  16399. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16400. // Bind last to it
  16401. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16402. // Bind to dummy
  16403. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16404. };
  16405. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16406. if (!internalTexture) {
  16407. return -1;
  16408. }
  16409. internalTexture._initialSlot = channel;
  16410. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16411. if (channel !== internalTexture._designatedSlot) {
  16412. this._textureCollisions.addCount(1, false);
  16413. }
  16414. }
  16415. else {
  16416. if (channel !== internalTexture._designatedSlot) {
  16417. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16418. return internalTexture._designatedSlot;
  16419. }
  16420. else {
  16421. // No slot for this texture, let's pick a new one (if we find a free slot)
  16422. if (this._nextFreeTextureSlots.length) {
  16423. return this._nextFreeTextureSlots[0];
  16424. }
  16425. // We need to recycle the oldest bound texture, sorry.
  16426. this._textureCollisions.addCount(1, false);
  16427. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16428. }
  16429. }
  16430. }
  16431. return channel;
  16432. };
  16433. Engine.prototype._linkTrackers = function (previous, next) {
  16434. previous.next = next;
  16435. next.previous = previous;
  16436. };
  16437. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16438. var currentSlot = internalTexture._designatedSlot;
  16439. if (currentSlot === -1) {
  16440. return -1;
  16441. }
  16442. internalTexture._designatedSlot = -1;
  16443. if (this.disableTextureBindingOptimization) {
  16444. return -1;
  16445. }
  16446. // Remove from bound list
  16447. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16448. // Free the slot
  16449. this._boundTexturesCache[currentSlot] = null;
  16450. this._nextFreeTextureSlots.push(currentSlot);
  16451. return currentSlot;
  16452. };
  16453. Engine.prototype._activateCurrentTexture = function () {
  16454. if (this._currentTextureChannel !== this._activeChannel) {
  16455. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16456. this._currentTextureChannel = this._activeChannel;
  16457. }
  16458. };
  16459. /** @hidden */
  16460. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16461. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16462. if (force === void 0) { force = false; }
  16463. var wasPreviouslyBound = false;
  16464. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16465. this._activeChannel = texture._designatedSlot;
  16466. }
  16467. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16468. var isTextureForRendering = texture && texture._initialSlot > -1;
  16469. if (currentTextureBound !== texture || force) {
  16470. if (currentTextureBound) {
  16471. this._removeDesignatedSlot(currentTextureBound);
  16472. }
  16473. this._activateCurrentTexture();
  16474. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16475. this._boundTexturesCache[this._activeChannel] = texture;
  16476. if (texture) {
  16477. if (!this.disableTextureBindingOptimization) {
  16478. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16479. if (slotIndex > -1) {
  16480. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16481. }
  16482. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16483. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16484. }
  16485. texture._designatedSlot = this._activeChannel;
  16486. }
  16487. }
  16488. else if (forTextureDataUpdate) {
  16489. wasPreviouslyBound = true;
  16490. this._activateCurrentTexture();
  16491. }
  16492. if (isTextureForRendering && !forTextureDataUpdate) {
  16493. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16494. }
  16495. return wasPreviouslyBound;
  16496. };
  16497. /** @hidden */
  16498. Engine.prototype._bindTexture = function (channel, texture) {
  16499. if (channel < 0) {
  16500. return;
  16501. }
  16502. if (texture) {
  16503. channel = this._getCorrectTextureChannel(channel, texture);
  16504. }
  16505. this._activeChannel = channel;
  16506. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16507. };
  16508. /**
  16509. * Sets a texture to the webGL context from a postprocess
  16510. * @param channel defines the channel to use
  16511. * @param postProcess defines the source postprocess
  16512. */
  16513. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16514. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16515. };
  16516. /**
  16517. * Binds the output of the passed in post process to the texture channel specified
  16518. * @param channel The channel the texture should be bound to
  16519. * @param postProcess The post process which's output should be bound
  16520. */
  16521. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16522. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16523. };
  16524. /**
  16525. * Unbind all textures from the webGL context
  16526. */
  16527. Engine.prototype.unbindAllTextures = function () {
  16528. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16529. this._activeChannel = channel;
  16530. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16531. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16532. if (this.webGLVersion > 1) {
  16533. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16534. }
  16535. }
  16536. };
  16537. /**
  16538. * Sets a texture to the according uniform.
  16539. * @param channel The texture channel
  16540. * @param uniform The uniform to set
  16541. * @param texture The texture to apply
  16542. */
  16543. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16544. if (channel < 0) {
  16545. return;
  16546. }
  16547. if (uniform) {
  16548. this._boundUniforms[channel] = uniform;
  16549. }
  16550. this._setTexture(channel, texture);
  16551. };
  16552. /**
  16553. * Sets a depth stencil texture from a render target to the according uniform.
  16554. * @param channel The texture channel
  16555. * @param uniform The uniform to set
  16556. * @param texture The render target texture containing the depth stencil texture to apply
  16557. */
  16558. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16559. if (channel < 0) {
  16560. return;
  16561. }
  16562. if (uniform) {
  16563. this._boundUniforms[channel] = uniform;
  16564. }
  16565. if (!texture || !texture.depthStencilTexture) {
  16566. this._setTexture(channel, null);
  16567. }
  16568. else {
  16569. this._setTexture(channel, texture, false, true);
  16570. }
  16571. };
  16572. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16573. var uniform = this._boundUniforms[sourceSlot];
  16574. if (uniform._currentState === destination) {
  16575. return;
  16576. }
  16577. this._gl.uniform1i(uniform, destination);
  16578. uniform._currentState = destination;
  16579. };
  16580. Engine.prototype._getTextureWrapMode = function (mode) {
  16581. switch (mode) {
  16582. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16583. return this._gl.REPEAT;
  16584. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16585. return this._gl.CLAMP_TO_EDGE;
  16586. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16587. return this._gl.MIRRORED_REPEAT;
  16588. }
  16589. return this._gl.REPEAT;
  16590. };
  16591. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16592. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16593. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16594. // Not ready?
  16595. if (!texture) {
  16596. if (this._boundTexturesCache[channel] != null) {
  16597. this._activeChannel = channel;
  16598. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16599. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16600. if (this.webGLVersion > 1) {
  16601. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16602. }
  16603. }
  16604. return false;
  16605. }
  16606. // Video
  16607. if (texture.video) {
  16608. this._activeChannel = channel;
  16609. texture.update();
  16610. }
  16611. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16612. texture.delayLoad();
  16613. return false;
  16614. }
  16615. var internalTexture;
  16616. if (depthStencilTexture) {
  16617. internalTexture = texture.depthStencilTexture;
  16618. }
  16619. else if (texture.isReady()) {
  16620. internalTexture = texture.getInternalTexture();
  16621. }
  16622. else if (texture.isCube) {
  16623. internalTexture = this.emptyCubeTexture;
  16624. }
  16625. else if (texture.is3D) {
  16626. internalTexture = this.emptyTexture3D;
  16627. }
  16628. else {
  16629. internalTexture = this.emptyTexture;
  16630. }
  16631. if (!isPartOfTextureArray) {
  16632. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16633. }
  16634. var needToBind = true;
  16635. if (this._boundTexturesCache[channel] === internalTexture) {
  16636. this._moveBoundTextureOnTop(internalTexture);
  16637. if (!isPartOfTextureArray) {
  16638. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16639. }
  16640. needToBind = false;
  16641. }
  16642. this._activeChannel = channel;
  16643. if (internalTexture && internalTexture.is3D) {
  16644. if (needToBind) {
  16645. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16646. }
  16647. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16648. internalTexture._cachedWrapU = texture.wrapU;
  16649. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16650. }
  16651. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16652. internalTexture._cachedWrapV = texture.wrapV;
  16653. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16654. }
  16655. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16656. internalTexture._cachedWrapR = texture.wrapR;
  16657. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16658. }
  16659. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16660. }
  16661. else if (internalTexture && internalTexture.isCube) {
  16662. if (needToBind) {
  16663. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16664. }
  16665. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16666. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16667. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16668. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16669. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16670. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16671. }
  16672. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16673. }
  16674. else {
  16675. if (needToBind) {
  16676. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16677. }
  16678. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16679. internalTexture._cachedWrapU = texture.wrapU;
  16680. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16681. }
  16682. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16683. internalTexture._cachedWrapV = texture.wrapV;
  16684. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16685. }
  16686. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16687. }
  16688. return true;
  16689. };
  16690. /**
  16691. * Sets an array of texture to the webGL context
  16692. * @param channel defines the channel where the texture array must be set
  16693. * @param uniform defines the associated uniform location
  16694. * @param textures defines the array of textures to bind
  16695. */
  16696. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16697. if (channel < 0 || !uniform) {
  16698. return;
  16699. }
  16700. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16701. this._textureUnits = new Int32Array(textures.length);
  16702. }
  16703. for (var i = 0; i < textures.length; i++) {
  16704. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16705. }
  16706. this._gl.uniform1iv(uniform, this._textureUnits);
  16707. for (var index = 0; index < textures.length; index++) {
  16708. this._setTexture(this._textureUnits[index], textures[index], true);
  16709. }
  16710. };
  16711. /** @hidden */
  16712. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16713. var internalTexture = texture.getInternalTexture();
  16714. if (!internalTexture) {
  16715. return;
  16716. }
  16717. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16718. var value = texture.anisotropicFilteringLevel;
  16719. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16720. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16721. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16722. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16723. }
  16724. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16725. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16726. internalTexture._cachedAnisotropicFilteringLevel = value;
  16727. }
  16728. };
  16729. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16730. this._bindTextureDirectly(target, texture, true, true);
  16731. this._gl.texParameterf(target, parameter, value);
  16732. };
  16733. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16734. if (texture) {
  16735. this._bindTextureDirectly(target, texture, true, true);
  16736. }
  16737. this._gl.texParameteri(target, parameter, value);
  16738. };
  16739. /**
  16740. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16741. * @param x defines the x coordinate of the rectangle where pixels must be read
  16742. * @param y defines the y coordinate of the rectangle where pixels must be read
  16743. * @param width defines the width of the rectangle where pixels must be read
  16744. * @param height defines the height of the rectangle where pixels must be read
  16745. * @returns a Uint8Array containing RGBA colors
  16746. */
  16747. Engine.prototype.readPixels = function (x, y, width, height) {
  16748. var data = new Uint8Array(height * width * 4);
  16749. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16750. return data;
  16751. };
  16752. /**
  16753. * Add an externaly attached data from its key.
  16754. * This method call will fail and return false, if such key already exists.
  16755. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16756. * @param key the unique key that identifies the data
  16757. * @param data the data object to associate to the key for this Engine instance
  16758. * @return true if no such key were already present and the data was added successfully, false otherwise
  16759. */
  16760. Engine.prototype.addExternalData = function (key, data) {
  16761. if (!this._externalData) {
  16762. this._externalData = new BABYLON.StringDictionary();
  16763. }
  16764. return this._externalData.add(key, data);
  16765. };
  16766. /**
  16767. * Get an externaly attached data from its key
  16768. * @param key the unique key that identifies the data
  16769. * @return the associated data, if present (can be null), or undefined if not present
  16770. */
  16771. Engine.prototype.getExternalData = function (key) {
  16772. if (!this._externalData) {
  16773. this._externalData = new BABYLON.StringDictionary();
  16774. }
  16775. return this._externalData.get(key);
  16776. };
  16777. /**
  16778. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16779. * @param key the unique key that identifies the data
  16780. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16781. * @return the associated data, can be null if the factory returned null.
  16782. */
  16783. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16784. if (!this._externalData) {
  16785. this._externalData = new BABYLON.StringDictionary();
  16786. }
  16787. return this._externalData.getOrAddWithFactory(key, factory);
  16788. };
  16789. /**
  16790. * Remove an externaly attached data from the Engine instance
  16791. * @param key the unique key that identifies the data
  16792. * @return true if the data was successfully removed, false if it doesn't exist
  16793. */
  16794. Engine.prototype.removeExternalData = function (key) {
  16795. if (!this._externalData) {
  16796. this._externalData = new BABYLON.StringDictionary();
  16797. }
  16798. return this._externalData.remove(key);
  16799. };
  16800. /**
  16801. * Unbind all vertex attributes from the webGL context
  16802. */
  16803. Engine.prototype.unbindAllAttributes = function () {
  16804. if (this._mustWipeVertexAttributes) {
  16805. this._mustWipeVertexAttributes = false;
  16806. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16807. this._gl.disableVertexAttribArray(i);
  16808. this._vertexAttribArraysEnabled[i] = false;
  16809. this._currentBufferPointers[i].active = false;
  16810. }
  16811. return;
  16812. }
  16813. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16814. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16815. continue;
  16816. }
  16817. this._gl.disableVertexAttribArray(i);
  16818. this._vertexAttribArraysEnabled[i] = false;
  16819. this._currentBufferPointers[i].active = false;
  16820. }
  16821. };
  16822. /**
  16823. * 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
  16824. */
  16825. Engine.prototype.releaseEffects = function () {
  16826. for (var name in this._compiledEffects) {
  16827. this._deleteProgram(this._compiledEffects[name]._program);
  16828. }
  16829. this._compiledEffects = {};
  16830. };
  16831. /**
  16832. * Dispose and release all associated resources
  16833. */
  16834. Engine.prototype.dispose = function () {
  16835. this.hideLoadingUI();
  16836. this.stopRenderLoop();
  16837. // Release postProcesses
  16838. while (this.postProcesses.length) {
  16839. this.postProcesses[0].dispose();
  16840. }
  16841. // Empty texture
  16842. if (this._emptyTexture) {
  16843. this._releaseTexture(this._emptyTexture);
  16844. this._emptyTexture = null;
  16845. }
  16846. if (this._emptyCubeTexture) {
  16847. this._releaseTexture(this._emptyCubeTexture);
  16848. this._emptyCubeTexture = null;
  16849. }
  16850. // Rescale PP
  16851. if (this._rescalePostProcess) {
  16852. this._rescalePostProcess.dispose();
  16853. }
  16854. // Release scenes
  16855. while (this.scenes.length) {
  16856. this.scenes[0].dispose();
  16857. }
  16858. // Release audio engine
  16859. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16860. Engine.audioEngine.dispose();
  16861. }
  16862. // Release effects
  16863. this.releaseEffects();
  16864. // Unbind
  16865. this.unbindAllAttributes();
  16866. this._boundUniforms = [];
  16867. if (this._dummyFramebuffer) {
  16868. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16869. }
  16870. //WebVR
  16871. this.disableVR();
  16872. // Events
  16873. if (BABYLON.Tools.IsWindowObjectExist()) {
  16874. window.removeEventListener("blur", this._onBlur);
  16875. window.removeEventListener("focus", this._onFocus);
  16876. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16877. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16878. if (this._renderingCanvas) {
  16879. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16880. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16881. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16882. if (!this._doNotHandleContextLost) {
  16883. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16884. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16885. }
  16886. }
  16887. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16888. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16889. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16890. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16891. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16892. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16893. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16894. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16895. if (this._onVrDisplayConnect) {
  16896. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16897. if (this._onVrDisplayDisconnect) {
  16898. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16899. }
  16900. if (this._onVrDisplayPresentChange) {
  16901. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16902. }
  16903. this._onVrDisplayConnect = null;
  16904. this._onVrDisplayDisconnect = null;
  16905. }
  16906. }
  16907. // Remove from Instances
  16908. var index = Engine.Instances.indexOf(this);
  16909. if (index >= 0) {
  16910. Engine.Instances.splice(index, 1);
  16911. }
  16912. this._workingCanvas = null;
  16913. this._workingContext = null;
  16914. this._currentBufferPointers = [];
  16915. this._renderingCanvas = null;
  16916. this._currentProgram = null;
  16917. this._bindedRenderFunction = null;
  16918. this.onResizeObservable.clear();
  16919. this.onCanvasBlurObservable.clear();
  16920. this.onCanvasFocusObservable.clear();
  16921. this.onCanvasPointerOutObservable.clear();
  16922. this.onBeginFrameObservable.clear();
  16923. this.onEndFrameObservable.clear();
  16924. BABYLON.Effect.ResetCache();
  16925. // Abort active requests
  16926. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16927. var request = _a[_i];
  16928. request.abort();
  16929. }
  16930. };
  16931. // Loading screen
  16932. /**
  16933. * Display the loading screen
  16934. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16935. */
  16936. Engine.prototype.displayLoadingUI = function () {
  16937. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16938. return;
  16939. }
  16940. var loadingScreen = this.loadingScreen;
  16941. if (loadingScreen) {
  16942. loadingScreen.displayLoadingUI();
  16943. }
  16944. };
  16945. /**
  16946. * Hide the loading screen
  16947. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16948. */
  16949. Engine.prototype.hideLoadingUI = function () {
  16950. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16951. return;
  16952. }
  16953. var loadingScreen = this.loadingScreen;
  16954. if (loadingScreen) {
  16955. loadingScreen.hideLoadingUI();
  16956. }
  16957. };
  16958. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16959. /**
  16960. * Gets the current loading screen object
  16961. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16962. */
  16963. get: function () {
  16964. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16965. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16966. return this._loadingScreen;
  16967. },
  16968. /**
  16969. * Sets the current loading screen object
  16970. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16971. */
  16972. set: function (loadingScreen) {
  16973. this._loadingScreen = loadingScreen;
  16974. },
  16975. enumerable: true,
  16976. configurable: true
  16977. });
  16978. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16979. /**
  16980. * Sets the current loading screen text
  16981. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16982. */
  16983. set: function (text) {
  16984. this.loadingScreen.loadingUIText = text;
  16985. },
  16986. enumerable: true,
  16987. configurable: true
  16988. });
  16989. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16990. /**
  16991. * Sets the current loading screen background color
  16992. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16993. */
  16994. set: function (color) {
  16995. this.loadingScreen.loadingUIBackgroundColor = color;
  16996. },
  16997. enumerable: true,
  16998. configurable: true
  16999. });
  17000. /**
  17001. * Attach a new callback raised when context lost event is fired
  17002. * @param callback defines the callback to call
  17003. */
  17004. Engine.prototype.attachContextLostEvent = function (callback) {
  17005. if (this._renderingCanvas) {
  17006. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17007. }
  17008. };
  17009. /**
  17010. * Attach a new callback raised when context restored event is fired
  17011. * @param callback defines the callback to call
  17012. */
  17013. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17014. if (this._renderingCanvas) {
  17015. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17016. }
  17017. };
  17018. /**
  17019. * Gets the source code of the vertex shader associated with a specific webGL program
  17020. * @param program defines the program to use
  17021. * @returns a string containing the source code of the vertex shader associated with the program
  17022. */
  17023. Engine.prototype.getVertexShaderSource = function (program) {
  17024. var shaders = this._gl.getAttachedShaders(program);
  17025. if (!shaders) {
  17026. return null;
  17027. }
  17028. return this._gl.getShaderSource(shaders[0]);
  17029. };
  17030. /**
  17031. * Gets the source code of the fragment shader associated with a specific webGL program
  17032. * @param program defines the program to use
  17033. * @returns a string containing the source code of the fragment shader associated with the program
  17034. */
  17035. Engine.prototype.getFragmentShaderSource = function (program) {
  17036. var shaders = this._gl.getAttachedShaders(program);
  17037. if (!shaders) {
  17038. return null;
  17039. }
  17040. return this._gl.getShaderSource(shaders[1]);
  17041. };
  17042. /**
  17043. * Get the current error code of the webGL context
  17044. * @returns the error code
  17045. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17046. */
  17047. Engine.prototype.getError = function () {
  17048. return this._gl.getError();
  17049. };
  17050. // FPS
  17051. /**
  17052. * Gets the current framerate
  17053. * @returns a number representing the framerate
  17054. */
  17055. Engine.prototype.getFps = function () {
  17056. return this._fps;
  17057. };
  17058. /**
  17059. * Gets the time spent between current and previous frame
  17060. * @returns a number representing the delta time in ms
  17061. */
  17062. Engine.prototype.getDeltaTime = function () {
  17063. return this._deltaTime;
  17064. };
  17065. Engine.prototype._measureFps = function () {
  17066. this._performanceMonitor.sampleFrame();
  17067. this._fps = this._performanceMonitor.averageFPS;
  17068. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17069. };
  17070. /** @hidden */
  17071. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17072. if (faceIndex === void 0) { faceIndex = -1; }
  17073. if (level === void 0) { level = 0; }
  17074. if (buffer === void 0) { buffer = null; }
  17075. var gl = this._gl;
  17076. if (!this._dummyFramebuffer) {
  17077. var dummy = gl.createFramebuffer();
  17078. if (!dummy) {
  17079. throw new Error("Unable to create dummy framebuffer");
  17080. }
  17081. this._dummyFramebuffer = dummy;
  17082. }
  17083. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17084. if (faceIndex > -1) {
  17085. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17086. }
  17087. else {
  17088. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17089. }
  17090. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17091. switch (readType) {
  17092. case gl.UNSIGNED_BYTE:
  17093. if (!buffer) {
  17094. buffer = new Uint8Array(4 * width * height);
  17095. }
  17096. readType = gl.UNSIGNED_BYTE;
  17097. break;
  17098. default:
  17099. if (!buffer) {
  17100. buffer = new Float32Array(4 * width * height);
  17101. }
  17102. readType = gl.FLOAT;
  17103. break;
  17104. }
  17105. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17106. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17107. return buffer;
  17108. };
  17109. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17110. if (this._webGLVersion > 1) {
  17111. return this._caps.colorBufferFloat;
  17112. }
  17113. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17114. };
  17115. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17116. if (this._webGLVersion > 1) {
  17117. return this._caps.colorBufferFloat;
  17118. }
  17119. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17120. };
  17121. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17122. Engine.prototype._canRenderToFramebuffer = function (type) {
  17123. var gl = this._gl;
  17124. //clear existing errors
  17125. while (gl.getError() !== gl.NO_ERROR) { }
  17126. var successful = true;
  17127. var texture = gl.createTexture();
  17128. gl.bindTexture(gl.TEXTURE_2D, texture);
  17129. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17130. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17131. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17132. var fb = gl.createFramebuffer();
  17133. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17134. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17135. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17136. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17137. successful = successful && (gl.getError() === gl.NO_ERROR);
  17138. //try render by clearing frame buffer's color buffer
  17139. if (successful) {
  17140. gl.clear(gl.COLOR_BUFFER_BIT);
  17141. successful = successful && (gl.getError() === gl.NO_ERROR);
  17142. }
  17143. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17144. if (successful) {
  17145. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17146. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17147. var readFormat = gl.RGBA;
  17148. var readType = gl.UNSIGNED_BYTE;
  17149. var buffer = new Uint8Array(4);
  17150. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17151. successful = successful && (gl.getError() === gl.NO_ERROR);
  17152. }
  17153. //clean up
  17154. gl.deleteTexture(texture);
  17155. gl.deleteFramebuffer(fb);
  17156. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17157. //clear accumulated errors
  17158. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17159. return successful;
  17160. };
  17161. /** @hidden */
  17162. Engine.prototype._getWebGLTextureType = function (type) {
  17163. if (this._webGLVersion === 1) {
  17164. switch (type) {
  17165. case Engine.TEXTURETYPE_FLOAT:
  17166. return this._gl.FLOAT;
  17167. case Engine.TEXTURETYPE_HALF_FLOAT:
  17168. return this._gl.HALF_FLOAT_OES;
  17169. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17170. return this._gl.UNSIGNED_BYTE;
  17171. }
  17172. return this._gl.UNSIGNED_BYTE;
  17173. }
  17174. switch (type) {
  17175. case Engine.TEXTURETYPE_BYTE:
  17176. return this._gl.BYTE;
  17177. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17178. return this._gl.UNSIGNED_BYTE;
  17179. case Engine.TEXTURETYPE_SHORT:
  17180. return this._gl.SHORT;
  17181. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17182. return this._gl.UNSIGNED_SHORT;
  17183. case Engine.TEXTURETYPE_INT:
  17184. return this._gl.INT;
  17185. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17186. return this._gl.UNSIGNED_INT;
  17187. case Engine.TEXTURETYPE_FLOAT:
  17188. return this._gl.FLOAT;
  17189. case Engine.TEXTURETYPE_HALF_FLOAT:
  17190. return this._gl.HALF_FLOAT;
  17191. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17192. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17193. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17194. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17195. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17196. return this._gl.UNSIGNED_SHORT_5_6_5;
  17197. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17198. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17199. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17200. return this._gl.UNSIGNED_INT_24_8;
  17201. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17202. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17203. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17204. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17205. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17206. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17207. }
  17208. return this._gl.UNSIGNED_BYTE;
  17209. };
  17210. ;
  17211. Engine.prototype._getInternalFormat = function (format) {
  17212. var internalFormat = this._gl.RGBA;
  17213. switch (format) {
  17214. case Engine.TEXTUREFORMAT_ALPHA:
  17215. internalFormat = this._gl.ALPHA;
  17216. break;
  17217. case Engine.TEXTUREFORMAT_LUMINANCE:
  17218. internalFormat = this._gl.LUMINANCE;
  17219. break;
  17220. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17221. internalFormat = this._gl.LUMINANCE_ALPHA;
  17222. break;
  17223. case Engine.TEXTUREFORMAT_RED:
  17224. internalFormat = this._gl.RED;
  17225. break;
  17226. case Engine.TEXTUREFORMAT_RG:
  17227. internalFormat = this._gl.RG;
  17228. break;
  17229. case Engine.TEXTUREFORMAT_RGB:
  17230. internalFormat = this._gl.RGB;
  17231. break;
  17232. case Engine.TEXTUREFORMAT_RGBA:
  17233. internalFormat = this._gl.RGBA;
  17234. break;
  17235. }
  17236. if (this._webGLVersion > 1) {
  17237. switch (format) {
  17238. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17239. internalFormat = this._gl.RED_INTEGER;
  17240. break;
  17241. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17242. internalFormat = this._gl.RG_INTEGER;
  17243. break;
  17244. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17245. internalFormat = this._gl.RGB_INTEGER;
  17246. break;
  17247. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17248. internalFormat = this._gl.RGBA_INTEGER;
  17249. break;
  17250. }
  17251. }
  17252. return internalFormat;
  17253. };
  17254. /** @hidden */
  17255. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17256. if (this._webGLVersion === 1) {
  17257. if (format !== undefined) {
  17258. switch (format) {
  17259. case Engine.TEXTUREFORMAT_ALPHA:
  17260. return this._gl.ALPHA;
  17261. case Engine.TEXTUREFORMAT_LUMINANCE:
  17262. return this._gl.LUMINANCE;
  17263. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17264. return this._gl.LUMINANCE_ALPHA;
  17265. }
  17266. }
  17267. return this._gl.RGBA;
  17268. }
  17269. switch (type) {
  17270. case Engine.TEXTURETYPE_BYTE:
  17271. switch (format) {
  17272. case Engine.TEXTUREFORMAT_RED:
  17273. return this._gl.R8_SNORM;
  17274. case Engine.TEXTUREFORMAT_RG:
  17275. return this._gl.RG8_SNORM;
  17276. case Engine.TEXTUREFORMAT_RGB:
  17277. return this._gl.RGB8_SNORM;
  17278. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17279. return this._gl.R8I;
  17280. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17281. return this._gl.RG8I;
  17282. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17283. return this._gl.RGB8I;
  17284. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17285. return this._gl.RGBA8I;
  17286. default:
  17287. return this._gl.RGBA8_SNORM;
  17288. }
  17289. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17290. switch (format) {
  17291. case Engine.TEXTUREFORMAT_RED:
  17292. return this._gl.R8;
  17293. case Engine.TEXTUREFORMAT_RG:
  17294. return this._gl.RG8;
  17295. case Engine.TEXTUREFORMAT_RGB:
  17296. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17297. case Engine.TEXTUREFORMAT_RGBA:
  17298. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17299. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17300. return this._gl.R8UI;
  17301. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17302. return this._gl.RG8UI;
  17303. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17304. return this._gl.RGB8UI;
  17305. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17306. return this._gl.RGBA8UI;
  17307. default:
  17308. return this._gl.RGBA8;
  17309. }
  17310. case Engine.TEXTURETYPE_SHORT:
  17311. switch (format) {
  17312. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17313. return this._gl.R16I;
  17314. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17315. return this._gl.RG16I;
  17316. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17317. return this._gl.RGB16I;
  17318. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17319. return this._gl.RGBA16I;
  17320. default:
  17321. return this._gl.RGBA16I;
  17322. }
  17323. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17324. switch (format) {
  17325. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17326. return this._gl.R16UI;
  17327. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17328. return this._gl.RG16UI;
  17329. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17330. return this._gl.RGB16UI;
  17331. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17332. return this._gl.RGBA16UI;
  17333. default:
  17334. return this._gl.RGBA16UI;
  17335. }
  17336. case Engine.TEXTURETYPE_INT:
  17337. switch (format) {
  17338. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17339. return this._gl.R32I;
  17340. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17341. return this._gl.RG32I;
  17342. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17343. return this._gl.RGB32I;
  17344. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17345. return this._gl.RGBA32I;
  17346. default:
  17347. return this._gl.RGBA32I;
  17348. }
  17349. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17350. switch (format) {
  17351. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17352. return this._gl.R32UI;
  17353. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17354. return this._gl.RG32UI;
  17355. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17356. return this._gl.RGB32UI;
  17357. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17358. return this._gl.RGBA32UI;
  17359. default:
  17360. return this._gl.RGBA32UI;
  17361. }
  17362. case Engine.TEXTURETYPE_FLOAT:
  17363. switch (format) {
  17364. case Engine.TEXTUREFORMAT_RED:
  17365. return this._gl.R32F; // By default. Other possibility is R16F.
  17366. case Engine.TEXTUREFORMAT_RG:
  17367. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17368. case Engine.TEXTUREFORMAT_RGB:
  17369. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17370. case Engine.TEXTUREFORMAT_RGBA:
  17371. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17372. default:
  17373. return this._gl.RGBA32F;
  17374. }
  17375. case Engine.TEXTURETYPE_HALF_FLOAT:
  17376. switch (format) {
  17377. case Engine.TEXTUREFORMAT_RED:
  17378. return this._gl.R16F;
  17379. case Engine.TEXTUREFORMAT_RG:
  17380. return this._gl.RG16F;
  17381. case Engine.TEXTUREFORMAT_RGB:
  17382. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17383. case Engine.TEXTUREFORMAT_RGBA:
  17384. return this._gl.RGBA16F;
  17385. default:
  17386. return this._gl.RGBA16F;
  17387. }
  17388. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17389. return this._gl.RGB565;
  17390. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17391. return this._gl.R11F_G11F_B10F;
  17392. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17393. return this._gl.RGB9_E5;
  17394. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17395. return this._gl.RGBA4;
  17396. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17397. return this._gl.RGB5_A1;
  17398. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17399. switch (format) {
  17400. case Engine.TEXTUREFORMAT_RGBA:
  17401. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17402. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17403. return this._gl.RGB10_A2UI;
  17404. default:
  17405. return this._gl.RGB10_A2;
  17406. }
  17407. }
  17408. return this._gl.RGBA8;
  17409. };
  17410. ;
  17411. /** @hidden */
  17412. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17413. if (type === Engine.TEXTURETYPE_FLOAT) {
  17414. return this._gl.RGBA32F;
  17415. }
  17416. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17417. return this._gl.RGBA16F;
  17418. }
  17419. return this._gl.RGBA8;
  17420. };
  17421. ;
  17422. /** @hidden */
  17423. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17424. var _this = this;
  17425. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17426. this._activeRequests.push(request);
  17427. request.onCompleteObservable.add(function (request) {
  17428. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17429. });
  17430. return request;
  17431. };
  17432. /** @hidden */
  17433. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17434. var _this = this;
  17435. return new Promise(function (resolve, reject) {
  17436. _this._loadFile(url, function (data) {
  17437. resolve(data);
  17438. }, undefined, database, useArrayBuffer, function (request, exception) {
  17439. reject(exception);
  17440. });
  17441. });
  17442. };
  17443. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17444. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17445. var onload = function (data) {
  17446. loadedFiles[index] = data;
  17447. loadedFiles._internalCount++;
  17448. if (loadedFiles._internalCount === 6) {
  17449. onfinish(loadedFiles);
  17450. }
  17451. };
  17452. var onerror = function (request, exception) {
  17453. if (onErrorCallBack && request) {
  17454. onErrorCallBack(request.status + " " + request.statusText, exception);
  17455. }
  17456. };
  17457. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17458. };
  17459. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17460. if (onError === void 0) { onError = null; }
  17461. var loadedFiles = [];
  17462. loadedFiles._internalCount = 0;
  17463. for (var index = 0; index < 6; index++) {
  17464. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17465. }
  17466. };
  17467. // Statics
  17468. /**
  17469. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17470. * @returns true if the engine can be created
  17471. * @ignorenaming
  17472. */
  17473. Engine.isSupported = function () {
  17474. try {
  17475. var tempcanvas = document.createElement("canvas");
  17476. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17477. return gl != null && !!window.WebGLRenderingContext;
  17478. }
  17479. catch (e) {
  17480. return false;
  17481. }
  17482. };
  17483. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17484. Engine.ExceptionList = [
  17485. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17486. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17487. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17488. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17489. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17490. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17491. ];
  17492. /** Gets the list of created engines */
  17493. Engine.Instances = new Array();
  17494. /**
  17495. * Hidden
  17496. */
  17497. Engine._TextureLoaders = [];
  17498. // Const statics
  17499. /** Defines that alpha blending is disabled */
  17500. Engine.ALPHA_DISABLE = 0;
  17501. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17502. Engine.ALPHA_ADD = 1;
  17503. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17504. Engine.ALPHA_COMBINE = 2;
  17505. /** Defines that alpha blending to DEST - SRC * DEST */
  17506. Engine.ALPHA_SUBTRACT = 3;
  17507. /** Defines that alpha blending to SRC * DEST */
  17508. Engine.ALPHA_MULTIPLY = 4;
  17509. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17510. Engine.ALPHA_MAXIMIZED = 5;
  17511. /** Defines that alpha blending to SRC + DEST */
  17512. Engine.ALPHA_ONEONE = 6;
  17513. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17514. Engine.ALPHA_PREMULTIPLIED = 7;
  17515. /**
  17516. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17517. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17518. */
  17519. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17520. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17521. Engine.ALPHA_INTERPOLATE = 9;
  17522. /**
  17523. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17524. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17525. */
  17526. Engine.ALPHA_SCREENMODE = 10;
  17527. /** Defines that the ressource is not delayed*/
  17528. Engine.DELAYLOADSTATE_NONE = 0;
  17529. /** Defines that the ressource was successfully delay loaded */
  17530. Engine.DELAYLOADSTATE_LOADED = 1;
  17531. /** Defines that the ressource is currently delay loading */
  17532. Engine.DELAYLOADSTATE_LOADING = 2;
  17533. /** Defines that the ressource is delayed and has not started loading */
  17534. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17535. // Depht or Stencil test Constants.
  17536. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17537. Engine.NEVER = 0x0200;
  17538. /** 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 */
  17539. Engine.ALWAYS = 0x0207;
  17540. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17541. Engine.LESS = 0x0201;
  17542. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17543. Engine.EQUAL = 0x0202;
  17544. /** 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 */
  17545. Engine.LEQUAL = 0x0203;
  17546. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17547. Engine.GREATER = 0x0204;
  17548. /** 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 */
  17549. Engine.GEQUAL = 0x0206;
  17550. /** 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 */
  17551. Engine.NOTEQUAL = 0x0205;
  17552. // Stencil Actions Constants.
  17553. /** Passed to stencilOperation to specify that stencil value must be kept */
  17554. Engine.KEEP = 0x1E00;
  17555. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17556. Engine.REPLACE = 0x1E01;
  17557. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17558. Engine.INCR = 0x1E02;
  17559. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17560. Engine.DECR = 0x1E03;
  17561. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17562. Engine.INVERT = 0x150A;
  17563. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17564. Engine.INCR_WRAP = 0x8507;
  17565. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17566. Engine.DECR_WRAP = 0x8508;
  17567. /** Texture is not repeating outside of 0..1 UVs */
  17568. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17569. /** Texture is repeating outside of 0..1 UVs */
  17570. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17571. /** Texture is repeating and mirrored */
  17572. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17573. /** ALPHA */
  17574. Engine.TEXTUREFORMAT_ALPHA = 0;
  17575. /** LUMINANCE */
  17576. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17577. /** LUMINANCE_ALPHA */
  17578. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17579. /** RGB */
  17580. Engine.TEXTUREFORMAT_RGB = 4;
  17581. /** RGBA */
  17582. Engine.TEXTUREFORMAT_RGBA = 5;
  17583. /** RED */
  17584. Engine.TEXTUREFORMAT_RED = 6;
  17585. /** RED (2nd reference) */
  17586. Engine.TEXTUREFORMAT_R = 6;
  17587. /** RG */
  17588. Engine.TEXTUREFORMAT_RG = 7;
  17589. /** RED_INTEGER */
  17590. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17591. /** RED_INTEGER (2nd reference) */
  17592. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17593. /** RG_INTEGER */
  17594. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17595. /** RGB_INTEGER */
  17596. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17597. /** RGBA_INTEGER */
  17598. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17599. /** UNSIGNED_BYTE */
  17600. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17601. /** UNSIGNED_BYTE (2nd reference) */
  17602. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17603. /** FLOAT */
  17604. Engine.TEXTURETYPE_FLOAT = 1;
  17605. /** HALF_FLOAT */
  17606. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17607. /** BYTE */
  17608. Engine.TEXTURETYPE_BYTE = 3;
  17609. /** SHORT */
  17610. Engine.TEXTURETYPE_SHORT = 4;
  17611. /** UNSIGNED_SHORT */
  17612. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17613. /** INT */
  17614. Engine.TEXTURETYPE_INT = 6;
  17615. /** UNSIGNED_INT */
  17616. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17617. /** UNSIGNED_SHORT_4_4_4_4 */
  17618. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17619. /** UNSIGNED_SHORT_5_5_5_1 */
  17620. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17621. /** UNSIGNED_SHORT_5_6_5 */
  17622. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17623. /** UNSIGNED_INT_2_10_10_10_REV */
  17624. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17625. /** UNSIGNED_INT_24_8 */
  17626. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17627. /** UNSIGNED_INT_10F_11F_11F_REV */
  17628. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17629. /** UNSIGNED_INT_5_9_9_9_REV */
  17630. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17631. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17632. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17633. /** nearest is mag = nearest and min = nearest and mip = linear */
  17634. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17635. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17636. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17637. /** Trilinear is mag = linear and min = linear and mip = linear */
  17638. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17639. /** nearest is mag = nearest and min = nearest and mip = linear */
  17640. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17641. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17642. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17643. /** Trilinear is mag = linear and min = linear and mip = linear */
  17644. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17645. /** mag = nearest and min = nearest and mip = nearest */
  17646. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17647. /** mag = nearest and min = linear and mip = nearest */
  17648. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17649. /** mag = nearest and min = linear and mip = linear */
  17650. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17651. /** mag = nearest and min = linear and mip = none */
  17652. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17653. /** mag = nearest and min = nearest and mip = none */
  17654. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17655. /** mag = linear and min = nearest and mip = nearest */
  17656. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17657. /** mag = linear and min = nearest and mip = linear */
  17658. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17659. /** mag = linear and min = linear and mip = none */
  17660. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17661. /** mag = linear and min = nearest and mip = none */
  17662. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17663. /** Explicit coordinates mode */
  17664. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17665. /** Spherical coordinates mode */
  17666. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17667. /** Planar coordinates mode */
  17668. Engine.TEXTURE_PLANAR_MODE = 2;
  17669. /** Cubic coordinates mode */
  17670. Engine.TEXTURE_CUBIC_MODE = 3;
  17671. /** Projection coordinates mode */
  17672. Engine.TEXTURE_PROJECTION_MODE = 4;
  17673. /** Skybox coordinates mode */
  17674. Engine.TEXTURE_SKYBOX_MODE = 5;
  17675. /** Inverse Cubic coordinates mode */
  17676. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17677. /** Equirectangular coordinates mode */
  17678. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17679. /** Equirectangular Fixed coordinates mode */
  17680. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17681. /** Equirectangular Fixed Mirrored coordinates mode */
  17682. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17683. // Texture rescaling mode
  17684. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17685. Engine.SCALEMODE_FLOOR = 1;
  17686. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17687. Engine.SCALEMODE_NEAREST = 2;
  17688. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17689. Engine.SCALEMODE_CEILING = 3;
  17690. // Updatable statics so stick with vars here
  17691. /**
  17692. * Gets or sets the epsilon value used by collision engine
  17693. */
  17694. Engine.CollisionsEpsilon = 0.001;
  17695. /**
  17696. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17697. */
  17698. Engine.CodeRepository = "src/";
  17699. /**
  17700. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17701. */
  17702. Engine.ShadersRepository = "src/Shaders/";
  17703. return Engine;
  17704. }());
  17705. BABYLON.Engine = Engine;
  17706. })(BABYLON || (BABYLON = {}));
  17707. //# sourceMappingURL=babylon.engine.js.map
  17708. var BABYLON;
  17709. (function (BABYLON) {
  17710. /**
  17711. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17712. */
  17713. var Node = /** @class */ (function () {
  17714. /**
  17715. * Creates a new Node
  17716. * @param {string} name - the name and id to be given to this node
  17717. * @param {BABYLON.Scene} the scene this node will be added to
  17718. */
  17719. function Node(name, scene) {
  17720. if (scene === void 0) { scene = null; }
  17721. /**
  17722. * Gets or sets a string used to store user defined state for the node
  17723. */
  17724. this.state = "";
  17725. /**
  17726. * Gets or sets an object used to store user defined information for the node
  17727. */
  17728. this.metadata = null;
  17729. /**
  17730. * Gets or sets a boolean used to define if the node must be serialized
  17731. */
  17732. this.doNotSerialize = false;
  17733. /** @hidden */
  17734. this._isDisposed = false;
  17735. /**
  17736. * Gets a list of Animations associated with the node
  17737. */
  17738. this.animations = new Array();
  17739. this._ranges = {};
  17740. this._isEnabled = true;
  17741. this._isParentEnabled = true;
  17742. this._isReady = true;
  17743. /** @hidden */
  17744. this._currentRenderId = -1;
  17745. this._parentRenderId = -1;
  17746. this._childRenderId = -1;
  17747. /** @hidden */
  17748. this._worldMatrix = BABYLON.Matrix.Identity();
  17749. /** @hidden */
  17750. this._worldMatrixDeterminant = 0;
  17751. this._animationPropertiesOverride = null;
  17752. /**
  17753. * An event triggered when the mesh is disposed
  17754. */
  17755. this.onDisposeObservable = new BABYLON.Observable();
  17756. // Behaviors
  17757. this._behaviors = new Array();
  17758. this.name = name;
  17759. this.id = name;
  17760. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17761. this.uniqueId = this._scene.getUniqueId();
  17762. this._initCache();
  17763. this._scene.rootNodes.push(this);
  17764. }
  17765. /**
  17766. * Add a new node constructor
  17767. * @param type defines the type name of the node to construct
  17768. * @param constructorFunc defines the constructor function
  17769. */
  17770. Node.AddNodeConstructor = function (type, constructorFunc) {
  17771. this._NodeConstructors[type] = constructorFunc;
  17772. };
  17773. /**
  17774. * Returns a node constructor based on type name
  17775. * @param type defines the type name
  17776. * @param name defines the new node name
  17777. * @param scene defines the hosting scene
  17778. * @param options defines optional options to transmit to constructors
  17779. * @returns the new constructor or null
  17780. */
  17781. Node.Construct = function (type, name, scene, options) {
  17782. var constructorFunc = this._NodeConstructors[type];
  17783. if (!constructorFunc) {
  17784. return null;
  17785. }
  17786. return constructorFunc(name, scene, options);
  17787. };
  17788. /**
  17789. * Gets a boolean indicating if the node has been disposed
  17790. * @returns true if the node was disposed
  17791. */
  17792. Node.prototype.isDisposed = function () {
  17793. return this._isDisposed;
  17794. };
  17795. Object.defineProperty(Node.prototype, "parent", {
  17796. get: function () {
  17797. return this._parentNode;
  17798. },
  17799. /**
  17800. * Gets or sets the parent of the node
  17801. */
  17802. set: function (parent) {
  17803. if (this._parentNode === parent) {
  17804. return;
  17805. }
  17806. var previousParentNode = this._parentNode;
  17807. // Remove self from list of children of parent
  17808. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17809. var index = this._parentNode._children.indexOf(this);
  17810. if (index !== -1) {
  17811. this._parentNode._children.splice(index, 1);
  17812. }
  17813. if (!parent) {
  17814. // Need to add this node to the rootNodes
  17815. this._scene.rootNodes.push(this);
  17816. }
  17817. }
  17818. // Store new parent
  17819. this._parentNode = parent;
  17820. // Add as child to new parent
  17821. if (this._parentNode) {
  17822. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17823. this._parentNode._children = new Array();
  17824. }
  17825. this._parentNode._children.push(this);
  17826. if (!previousParentNode) {
  17827. // Need to remove from rootNodes
  17828. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17829. if (rootNodeIndex > -1) {
  17830. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17831. }
  17832. }
  17833. }
  17834. // Enabled state
  17835. this._syncParentEnabledState();
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17841. /**
  17842. * Gets or sets the animation properties override
  17843. */
  17844. get: function () {
  17845. if (!this._animationPropertiesOverride) {
  17846. return this._scene.animationPropertiesOverride;
  17847. }
  17848. return this._animationPropertiesOverride;
  17849. },
  17850. set: function (value) {
  17851. this._animationPropertiesOverride = value;
  17852. },
  17853. enumerable: true,
  17854. configurable: true
  17855. });
  17856. /**
  17857. * Gets a string idenfifying the name of the class
  17858. * @returns "Node" string
  17859. */
  17860. Node.prototype.getClassName = function () {
  17861. return "Node";
  17862. };
  17863. Object.defineProperty(Node.prototype, "onDispose", {
  17864. /**
  17865. * Sets a callback that will be raised when the node will be disposed
  17866. */
  17867. set: function (callback) {
  17868. if (this._onDisposeObserver) {
  17869. this.onDisposeObservable.remove(this._onDisposeObserver);
  17870. }
  17871. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17872. },
  17873. enumerable: true,
  17874. configurable: true
  17875. });
  17876. /**
  17877. * Gets the scene of the node
  17878. * @returns a {BABYLON.Scene}
  17879. */
  17880. Node.prototype.getScene = function () {
  17881. return this._scene;
  17882. };
  17883. /**
  17884. * Gets the engine of the node
  17885. * @returns a {BABYLON.Engine}
  17886. */
  17887. Node.prototype.getEngine = function () {
  17888. return this._scene.getEngine();
  17889. };
  17890. /**
  17891. * Attach a behavior to the node
  17892. * @see http://doc.babylonjs.com/features/behaviour
  17893. * @param behavior defines the behavior to attach
  17894. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  17895. * @returns the current Node
  17896. */
  17897. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  17898. var _this = this;
  17899. if (attachImmediately === void 0) { attachImmediately = false; }
  17900. var index = this._behaviors.indexOf(behavior);
  17901. if (index !== -1) {
  17902. return this;
  17903. }
  17904. behavior.init();
  17905. if (this._scene.isLoading && !attachImmediately) {
  17906. // We defer the attach when the scene will be loaded
  17907. this._scene.onDataLoadedObservable.addOnce(function () {
  17908. behavior.attach(_this);
  17909. });
  17910. }
  17911. else {
  17912. behavior.attach(this);
  17913. }
  17914. this._behaviors.push(behavior);
  17915. return this;
  17916. };
  17917. /**
  17918. * Remove an attached behavior
  17919. * @see http://doc.babylonjs.com/features/behaviour
  17920. * @param behavior defines the behavior to attach
  17921. * @returns the current Node
  17922. */
  17923. Node.prototype.removeBehavior = function (behavior) {
  17924. var index = this._behaviors.indexOf(behavior);
  17925. if (index === -1) {
  17926. return this;
  17927. }
  17928. this._behaviors[index].detach();
  17929. this._behaviors.splice(index, 1);
  17930. return this;
  17931. };
  17932. Object.defineProperty(Node.prototype, "behaviors", {
  17933. /**
  17934. * Gets the list of attached behaviors
  17935. * @see http://doc.babylonjs.com/features/behaviour
  17936. */
  17937. get: function () {
  17938. return this._behaviors;
  17939. },
  17940. enumerable: true,
  17941. configurable: true
  17942. });
  17943. /**
  17944. * Gets an attached behavior by name
  17945. * @param name defines the name of the behavior to look for
  17946. * @see http://doc.babylonjs.com/features/behaviour
  17947. * @returns null if behavior was not found else the requested behavior
  17948. */
  17949. Node.prototype.getBehaviorByName = function (name) {
  17950. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17951. var behavior = _a[_i];
  17952. if (behavior.name === name) {
  17953. return behavior;
  17954. }
  17955. }
  17956. return null;
  17957. };
  17958. /**
  17959. * Returns the latest update of the World matrix
  17960. * @returns a Matrix
  17961. */
  17962. Node.prototype.getWorldMatrix = function () {
  17963. if (this._currentRenderId !== this._scene.getRenderId()) {
  17964. this.computeWorldMatrix();
  17965. }
  17966. return this._worldMatrix;
  17967. };
  17968. /** @hidden */
  17969. Node.prototype._getWorldMatrixDeterminant = function () {
  17970. return this._worldMatrixDeterminant;
  17971. };
  17972. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17973. /**
  17974. * Returns directly the latest state of the mesh World matrix.
  17975. * A Matrix is returned.
  17976. */
  17977. get: function () {
  17978. return this._worldMatrix;
  17979. },
  17980. enumerable: true,
  17981. configurable: true
  17982. });
  17983. // override it in derived class if you add new variables to the cache
  17984. // and call the parent class method
  17985. /** @hidden */
  17986. Node.prototype._initCache = function () {
  17987. this._cache = {};
  17988. this._cache.parent = undefined;
  17989. };
  17990. /** @hidden */
  17991. Node.prototype.updateCache = function (force) {
  17992. if (!force && this.isSynchronized())
  17993. return;
  17994. this._cache.parent = this.parent;
  17995. this._updateCache();
  17996. };
  17997. // override it in derived class if you add new variables to the cache
  17998. // and call the parent class method if !ignoreParentClass
  17999. /** @hidden */
  18000. Node.prototype._updateCache = function (ignoreParentClass) {
  18001. };
  18002. // override it in derived class if you add new variables to the cache
  18003. /** @hidden */
  18004. Node.prototype._isSynchronized = function () {
  18005. return true;
  18006. };
  18007. /** @hidden */
  18008. Node.prototype._markSyncedWithParent = function () {
  18009. if (this._parentNode) {
  18010. this._parentRenderId = this._parentNode._childRenderId;
  18011. }
  18012. };
  18013. /** @hidden */
  18014. Node.prototype.isSynchronizedWithParent = function () {
  18015. if (!this._parentNode) {
  18016. return true;
  18017. }
  18018. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18019. return false;
  18020. }
  18021. return this._parentNode.isSynchronized();
  18022. };
  18023. /** @hidden */
  18024. Node.prototype.isSynchronized = function () {
  18025. if (this._cache.parent != this._parentNode) {
  18026. this._cache.parent = this._parentNode;
  18027. return false;
  18028. }
  18029. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18030. return false;
  18031. }
  18032. return this._isSynchronized();
  18033. };
  18034. /**
  18035. * Is this node ready to be used/rendered
  18036. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18037. * @return true if the node is ready
  18038. */
  18039. Node.prototype.isReady = function (completeCheck) {
  18040. if (completeCheck === void 0) { completeCheck = false; }
  18041. return this._isReady;
  18042. };
  18043. /**
  18044. * Is this node enabled?
  18045. * 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
  18046. * @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
  18047. * @return whether this node (and its parent) is enabled
  18048. */
  18049. Node.prototype.isEnabled = function (checkAncestors) {
  18050. if (checkAncestors === void 0) { checkAncestors = true; }
  18051. if (checkAncestors === false) {
  18052. return this._isEnabled;
  18053. }
  18054. if (!this._isEnabled) {
  18055. return false;
  18056. }
  18057. return this._isParentEnabled;
  18058. };
  18059. /** @hidden */
  18060. Node.prototype._syncParentEnabledState = function () {
  18061. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18062. if (this._children) {
  18063. this._children.forEach(function (c) {
  18064. c._syncParentEnabledState(); // Force children to update accordingly
  18065. });
  18066. }
  18067. };
  18068. /**
  18069. * Set the enabled state of this node
  18070. * @param value defines the new enabled state
  18071. */
  18072. Node.prototype.setEnabled = function (value) {
  18073. this._isEnabled = value;
  18074. this._syncParentEnabledState();
  18075. };
  18076. /**
  18077. * Is this node a descendant of the given node?
  18078. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18079. * @param ancestor defines the parent node to inspect
  18080. * @returns a boolean indicating if this node is a descendant of the given node
  18081. */
  18082. Node.prototype.isDescendantOf = function (ancestor) {
  18083. if (this.parent) {
  18084. if (this.parent === ancestor) {
  18085. return true;
  18086. }
  18087. return this.parent.isDescendantOf(ancestor);
  18088. }
  18089. return false;
  18090. };
  18091. /** @hidden */
  18092. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18093. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18094. if (!this._children) {
  18095. return;
  18096. }
  18097. for (var index = 0; index < this._children.length; index++) {
  18098. var item = this._children[index];
  18099. if (!predicate || predicate(item)) {
  18100. results.push(item);
  18101. }
  18102. if (!directDescendantsOnly) {
  18103. item._getDescendants(results, false, predicate);
  18104. }
  18105. }
  18106. };
  18107. /**
  18108. * Will return all nodes that have this node as ascendant
  18109. * @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
  18110. * @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
  18111. * @return all children nodes of all types
  18112. */
  18113. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18114. var results = new Array();
  18115. this._getDescendants(results, directDescendantsOnly, predicate);
  18116. return results;
  18117. };
  18118. /**
  18119. * Get all child-meshes of this node
  18120. * @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
  18121. * @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
  18122. * @returns an array of {BABYLON.AbstractMesh}
  18123. */
  18124. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18125. var results = [];
  18126. this._getDescendants(results, directDescendantsOnly, function (node) {
  18127. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18128. });
  18129. return results;
  18130. };
  18131. /**
  18132. * Get all child-transformNodes of this node
  18133. * @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
  18134. * @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
  18135. * @returns an array of {BABYLON.TransformNode}
  18136. */
  18137. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18138. var results = [];
  18139. this._getDescendants(results, directDescendantsOnly, function (node) {
  18140. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18141. });
  18142. return results;
  18143. };
  18144. /**
  18145. * Get all direct children of this node
  18146. * @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
  18147. * @returns an array of {BABYLON.Node}
  18148. */
  18149. Node.prototype.getChildren = function (predicate) {
  18150. return this.getDescendants(true, predicate);
  18151. };
  18152. /** @hidden */
  18153. Node.prototype._setReady = function (state) {
  18154. if (state === this._isReady) {
  18155. return;
  18156. }
  18157. if (!state) {
  18158. this._isReady = false;
  18159. return;
  18160. }
  18161. if (this.onReady) {
  18162. this.onReady(this);
  18163. }
  18164. this._isReady = true;
  18165. };
  18166. /**
  18167. * Get an animation by name
  18168. * @param name defines the name of the animation to look for
  18169. * @returns null if not found else the requested animation
  18170. */
  18171. Node.prototype.getAnimationByName = function (name) {
  18172. for (var i = 0; i < this.animations.length; i++) {
  18173. var animation = this.animations[i];
  18174. if (animation.name === name) {
  18175. return animation;
  18176. }
  18177. }
  18178. return null;
  18179. };
  18180. /**
  18181. * Creates an animation range for this node
  18182. * @param name defines the name of the range
  18183. * @param from defines the starting key
  18184. * @param to defines the end key
  18185. */
  18186. Node.prototype.createAnimationRange = function (name, from, to) {
  18187. // check name not already in use
  18188. if (!this._ranges[name]) {
  18189. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18190. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18191. if (this.animations[i]) {
  18192. this.animations[i].createRange(name, from, to);
  18193. }
  18194. }
  18195. }
  18196. };
  18197. /**
  18198. * Delete a specific animation range
  18199. * @param name defines the name of the range to delete
  18200. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18201. */
  18202. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18203. if (deleteFrames === void 0) { deleteFrames = true; }
  18204. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18205. if (this.animations[i]) {
  18206. this.animations[i].deleteRange(name, deleteFrames);
  18207. }
  18208. }
  18209. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18210. };
  18211. /**
  18212. * Get an animation range by name
  18213. * @param name defines the name of the animation range to look for
  18214. * @returns null if not found else the requested animation range
  18215. */
  18216. Node.prototype.getAnimationRange = function (name) {
  18217. return this._ranges[name];
  18218. };
  18219. /**
  18220. * Will start the animation sequence
  18221. * @param name defines the range frames for animation sequence
  18222. * @param loop defines if the animation should loop (false by default)
  18223. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18224. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18225. * @returns the object created for this animation. If range does not exist, it will return null
  18226. */
  18227. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18228. var range = this.getAnimationRange(name);
  18229. if (!range) {
  18230. return null;
  18231. }
  18232. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18233. };
  18234. /**
  18235. * Serialize animation ranges into a JSON compatible object
  18236. * @returns serialization object
  18237. */
  18238. Node.prototype.serializeAnimationRanges = function () {
  18239. var serializationRanges = [];
  18240. for (var name in this._ranges) {
  18241. var localRange = this._ranges[name];
  18242. if (!localRange) {
  18243. continue;
  18244. }
  18245. var range = {};
  18246. range.name = name;
  18247. range.from = localRange.from;
  18248. range.to = localRange.to;
  18249. serializationRanges.push(range);
  18250. }
  18251. return serializationRanges;
  18252. };
  18253. /**
  18254. * Computes the world matrix of the node
  18255. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18256. * @returns the world matrix
  18257. */
  18258. Node.prototype.computeWorldMatrix = function (force) {
  18259. if (!this._worldMatrix) {
  18260. this._worldMatrix = BABYLON.Matrix.Identity();
  18261. }
  18262. return this._worldMatrix;
  18263. };
  18264. /**
  18265. * Releases resources associated with this node.
  18266. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18267. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18268. */
  18269. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18270. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18271. if (!doNotRecurse) {
  18272. var nodes = this.getDescendants(true);
  18273. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18274. var node = nodes_1[_i];
  18275. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18276. }
  18277. }
  18278. else {
  18279. var transformNodes = this.getChildTransformNodes(true);
  18280. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18281. var transformNode = transformNodes_1[_a];
  18282. transformNode.parent = null;
  18283. transformNode.computeWorldMatrix(true);
  18284. }
  18285. }
  18286. if (!this.parent) {
  18287. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18288. if (rootNodeIndex > -1) {
  18289. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18290. }
  18291. }
  18292. else {
  18293. this.parent = null;
  18294. }
  18295. // Callback
  18296. this.onDisposeObservable.notifyObservers(this);
  18297. this.onDisposeObservable.clear();
  18298. // Behaviors
  18299. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18300. var behavior = _c[_b];
  18301. behavior.detach();
  18302. }
  18303. this._behaviors = [];
  18304. this._isDisposed = true;
  18305. };
  18306. /**
  18307. * Parse animation range data from a serialization object and store them into a given node
  18308. * @param node defines where to store the animation ranges
  18309. * @param parsedNode defines the serialization object to read data from
  18310. * @param scene defines the hosting scene
  18311. */
  18312. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18313. if (parsedNode.ranges) {
  18314. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18315. var data = parsedNode.ranges[index];
  18316. node.createAnimationRange(data.name, data.from, data.to);
  18317. }
  18318. }
  18319. };
  18320. Node._NodeConstructors = {};
  18321. __decorate([
  18322. BABYLON.serialize()
  18323. ], Node.prototype, "name", void 0);
  18324. __decorate([
  18325. BABYLON.serialize()
  18326. ], Node.prototype, "id", void 0);
  18327. __decorate([
  18328. BABYLON.serialize()
  18329. ], Node.prototype, "uniqueId", void 0);
  18330. __decorate([
  18331. BABYLON.serialize()
  18332. ], Node.prototype, "state", void 0);
  18333. __decorate([
  18334. BABYLON.serialize()
  18335. ], Node.prototype, "metadata", void 0);
  18336. return Node;
  18337. }());
  18338. BABYLON.Node = Node;
  18339. })(BABYLON || (BABYLON = {}));
  18340. //# sourceMappingURL=babylon.node.js.map
  18341. var BABYLON;
  18342. (function (BABYLON) {
  18343. // This matrix is used as a value to reset the bounding box.
  18344. var _identityMatrix = BABYLON.Matrix.Identity();
  18345. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18346. var BoundingSphere = /** @class */ (function () {
  18347. /**
  18348. * Creates a new bounding sphere
  18349. * @param min defines the minimum vector (in local space)
  18350. * @param max defines the maximum vector (in local space)
  18351. */
  18352. function BoundingSphere(min, max) {
  18353. this.center = BABYLON.Vector3.Zero();
  18354. this.centerWorld = BABYLON.Vector3.Zero();
  18355. this.reConstruct(min, max);
  18356. }
  18357. /**
  18358. * Recreates the entire bounding sphere from scratch
  18359. * @param min defines the new minimum vector (in local space)
  18360. * @param max defines the new maximum vector (in local space)
  18361. */
  18362. BoundingSphere.prototype.reConstruct = function (min, max) {
  18363. this.minimum = min.clone();
  18364. this.maximum = max.clone();
  18365. var distance = BABYLON.Vector3.Distance(min, max);
  18366. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18367. this.radius = distance * 0.5;
  18368. this.centerWorld.set(0, 0, 0);
  18369. this._update(_identityMatrix);
  18370. };
  18371. /**
  18372. * Scale the current bounding sphere by applying a scale factor
  18373. * @param factor defines the scale factor to apply
  18374. * @returns the current bounding box
  18375. */
  18376. BoundingSphere.prototype.scale = function (factor) {
  18377. var newRadius = this.radius * factor;
  18378. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18379. var min = this.center.subtract(_tempRadiusVector);
  18380. var max = this.center.add(_tempRadiusVector);
  18381. this.reConstruct(min, max);
  18382. return this;
  18383. };
  18384. // Methods
  18385. /** @hidden */
  18386. BoundingSphere.prototype._update = function (world) {
  18387. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18388. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18389. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18390. };
  18391. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18392. for (var i = 0; i < 6; i++) {
  18393. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18394. return false;
  18395. }
  18396. return true;
  18397. };
  18398. BoundingSphere.prototype.intersectsPoint = function (point) {
  18399. var x = this.centerWorld.x - point.x;
  18400. var y = this.centerWorld.y - point.y;
  18401. var z = this.centerWorld.z - point.z;
  18402. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18403. if (this.radiusWorld < distance)
  18404. return false;
  18405. return true;
  18406. };
  18407. // Statics
  18408. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18409. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18410. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18411. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18412. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18413. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18414. return false;
  18415. return true;
  18416. };
  18417. return BoundingSphere;
  18418. }());
  18419. BABYLON.BoundingSphere = BoundingSphere;
  18420. })(BABYLON || (BABYLON = {}));
  18421. //# sourceMappingURL=babylon.boundingSphere.js.map
  18422. var BABYLON;
  18423. (function (BABYLON) {
  18424. /**
  18425. * Class used to store bounding box information
  18426. */
  18427. var BoundingBox = /** @class */ (function () {
  18428. /**
  18429. * Creates a new bounding box
  18430. * @param min defines the minimum vector (in local space)
  18431. * @param max defines the maximum vector (in local space)
  18432. */
  18433. function BoundingBox(min, max) {
  18434. /**
  18435. * Gets the 8 vectors representing the bounding box in world space
  18436. */
  18437. this.vectorsWorld = new Array();
  18438. this.reConstruct(min, max);
  18439. }
  18440. // Methods
  18441. /**
  18442. * Recreates the entire bounding box from scratch
  18443. * @param min defines the new minimum vector (in local space)
  18444. * @param max defines the new maximum vector (in local space)
  18445. */
  18446. BoundingBox.prototype.reConstruct = function (min, max) {
  18447. this.minimum = min.clone();
  18448. this.maximum = max.clone();
  18449. // Bounding vectors
  18450. this.vectors = [
  18451. this.minimum.clone(),
  18452. this.maximum.clone(),
  18453. this.minimum.clone(),
  18454. this.minimum.clone(),
  18455. this.minimum.clone(),
  18456. this.maximum.clone(),
  18457. this.maximum.clone(),
  18458. this.maximum.clone()
  18459. ];
  18460. this.vectors[2].x = this.maximum.x;
  18461. this.vectors[3].y = this.maximum.y;
  18462. this.vectors[4].z = this.maximum.z;
  18463. this.vectors[5].z = this.minimum.z;
  18464. this.vectors[6].x = this.minimum.x;
  18465. this.vectors[7].y = this.minimum.y;
  18466. // OBB
  18467. this.center = this.maximum.add(this.minimum).scale(0.5);
  18468. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18469. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18470. // World
  18471. for (var index = 0; index < this.vectors.length; index++) {
  18472. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18473. }
  18474. this.minimumWorld = BABYLON.Vector3.Zero();
  18475. this.maximumWorld = BABYLON.Vector3.Zero();
  18476. this.centerWorld = BABYLON.Vector3.Zero();
  18477. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18478. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18479. };
  18480. /**
  18481. * Scale the current bounding box by applying a scale factor
  18482. * @param factor defines the scale factor to apply
  18483. * @returns the current bounding box
  18484. */
  18485. BoundingBox.prototype.scale = function (factor) {
  18486. var diff = this.maximum.subtract(this.minimum);
  18487. var distance = diff.length() * factor;
  18488. diff.normalize();
  18489. var newRadius = diff.scale(distance / 2);
  18490. var min = this.center.subtract(newRadius);
  18491. var max = this.center.add(newRadius);
  18492. this.reConstruct(min, max);
  18493. return this;
  18494. };
  18495. /**
  18496. * Gets the world matrix of the bounding box
  18497. * @returns a matrix
  18498. */
  18499. BoundingBox.prototype.getWorldMatrix = function () {
  18500. return this._worldMatrix;
  18501. };
  18502. /**
  18503. * Sets the world matrix stored in the bounding box
  18504. * @param matrix defines the matrix to store
  18505. * @returns current bounding box
  18506. */
  18507. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18508. this._worldMatrix.copyFrom(matrix);
  18509. return this;
  18510. };
  18511. /** @hidden */
  18512. BoundingBox.prototype._update = function (world) {
  18513. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18514. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18515. for (var index = 0; index < this.vectors.length; index++) {
  18516. var v = this.vectorsWorld[index];
  18517. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18518. if (v.x < this.minimumWorld.x)
  18519. this.minimumWorld.x = v.x;
  18520. if (v.y < this.minimumWorld.y)
  18521. this.minimumWorld.y = v.y;
  18522. if (v.z < this.minimumWorld.z)
  18523. this.minimumWorld.z = v.z;
  18524. if (v.x > this.maximumWorld.x)
  18525. this.maximumWorld.x = v.x;
  18526. if (v.y > this.maximumWorld.y)
  18527. this.maximumWorld.y = v.y;
  18528. if (v.z > this.maximumWorld.z)
  18529. this.maximumWorld.z = v.z;
  18530. }
  18531. // Extend
  18532. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18533. this.extendSizeWorld.scaleInPlace(0.5);
  18534. // OBB
  18535. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18536. this.centerWorld.scaleInPlace(0.5);
  18537. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18538. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18539. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18540. this._worldMatrix = world;
  18541. };
  18542. /**
  18543. * Tests if the bounding box is intersecting the frustum planes
  18544. * @param frustumPlanes defines the frustum planes to test
  18545. * @returns true if there is an intersection
  18546. */
  18547. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18548. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18549. };
  18550. /**
  18551. * Tests if the bounding box is entirely inside the frustum planes
  18552. * @param frustumPlanes defines the frustum planes to test
  18553. * @returns true if there is an inclusion
  18554. */
  18555. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18556. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18557. };
  18558. /**
  18559. * Tests if a point is inside the bounding box
  18560. * @param point defines the point to test
  18561. * @returns true if the point is inside the bounding box
  18562. */
  18563. BoundingBox.prototype.intersectsPoint = function (point) {
  18564. var delta = -BABYLON.Epsilon;
  18565. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18566. return false;
  18567. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18568. return false;
  18569. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18570. return false;
  18571. return true;
  18572. };
  18573. /**
  18574. * Tests if the bounding box intersects with a bounding sphere
  18575. * @param sphere defines the sphere to test
  18576. * @returns true if there is an intersection
  18577. */
  18578. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18579. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18580. };
  18581. /**
  18582. * Tests if the bounding box intersects with a box defined by a min and max vectors
  18583. * @param min defines the min vector to use
  18584. * @param max defines the max vector to use
  18585. * @returns true if there is an intersection
  18586. */
  18587. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18588. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18589. return false;
  18590. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18591. return false;
  18592. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18593. return false;
  18594. return true;
  18595. };
  18596. // Statics
  18597. /**
  18598. * Tests if two bounding boxes are intersections
  18599. * @param box0 defines the first box to test
  18600. * @param box1 defines the second box to test
  18601. * @returns true if there is an intersection
  18602. */
  18603. BoundingBox.Intersects = function (box0, box1) {
  18604. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18605. return false;
  18606. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18607. return false;
  18608. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18609. return false;
  18610. return true;
  18611. };
  18612. /**
  18613. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  18614. * @param minPoint defines the minimum vector of the bounding box
  18615. * @param maxPoint defines the maximum vector of the bounding box
  18616. * @param sphereCenter defines the sphere center
  18617. * @param sphereRadius defines the sphere radius
  18618. * @returns true if there is an intersection
  18619. */
  18620. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18621. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18622. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18623. return (num <= (sphereRadius * sphereRadius));
  18624. };
  18625. /**
  18626. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  18627. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18628. * @param frustumPlanes defines the frustum planes to test
  18629. * @return true if there is an inclusion
  18630. */
  18631. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18632. for (var p = 0; p < 6; p++) {
  18633. for (var i = 0; i < 8; i++) {
  18634. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18635. return false;
  18636. }
  18637. }
  18638. }
  18639. return true;
  18640. };
  18641. /**
  18642. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  18643. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  18644. * @param frustumPlanes defines the frustum planes to test
  18645. * @return true if there is an intersection
  18646. */
  18647. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18648. for (var p = 0; p < 6; p++) {
  18649. var inCount = 8;
  18650. for (var i = 0; i < 8; i++) {
  18651. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18652. --inCount;
  18653. }
  18654. else {
  18655. break;
  18656. }
  18657. }
  18658. if (inCount === 0)
  18659. return false;
  18660. }
  18661. return true;
  18662. };
  18663. return BoundingBox;
  18664. }());
  18665. BABYLON.BoundingBox = BoundingBox;
  18666. })(BABYLON || (BABYLON = {}));
  18667. //# sourceMappingURL=babylon.boundingBox.js.map
  18668. var BABYLON;
  18669. (function (BABYLON) {
  18670. var computeBoxExtents = function (axis, box) {
  18671. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18672. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18673. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18674. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18675. var r = r0 + r1 + r2;
  18676. return {
  18677. min: p - r,
  18678. max: p + r
  18679. };
  18680. };
  18681. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18682. var axisOverlap = function (axis, box0, box1) {
  18683. var result0 = computeBoxExtents(axis, box0);
  18684. var result1 = computeBoxExtents(axis, box1);
  18685. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18686. };
  18687. var BoundingInfo = /** @class */ (function () {
  18688. function BoundingInfo(minimum, maximum) {
  18689. this.minimum = minimum;
  18690. this.maximum = maximum;
  18691. this._isLocked = false;
  18692. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18693. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18694. }
  18695. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18696. get: function () {
  18697. return this._isLocked;
  18698. },
  18699. set: function (value) {
  18700. this._isLocked = value;
  18701. },
  18702. enumerable: true,
  18703. configurable: true
  18704. });
  18705. // Methods
  18706. BoundingInfo.prototype.update = function (world) {
  18707. if (this._isLocked) {
  18708. return;
  18709. }
  18710. this.boundingBox._update(world);
  18711. this.boundingSphere._update(world);
  18712. };
  18713. /**
  18714. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18715. * @param center New center of the bounding info
  18716. * @param extend New extend of the bounding info
  18717. */
  18718. BoundingInfo.prototype.centerOn = function (center, extend) {
  18719. this.minimum = center.subtract(extend);
  18720. this.maximum = center.add(extend);
  18721. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18722. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18723. return this;
  18724. };
  18725. /**
  18726. * Scale the current bounding info by applying a scale factor
  18727. * @param factor defines the scale factor to apply
  18728. * @returns the current bounding info
  18729. */
  18730. BoundingInfo.prototype.scale = function (factor) {
  18731. this.boundingBox.scale(factor);
  18732. this.boundingSphere.scale(factor);
  18733. return this;
  18734. };
  18735. /**
  18736. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18737. * @param frustumPlanes defines the frustum to test
  18738. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18739. * @returns true if the bounding info is in the frustum planes
  18740. */
  18741. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18742. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18743. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18744. return false;
  18745. }
  18746. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18747. return true;
  18748. }
  18749. return this.boundingBox.isInFrustum(frustumPlanes);
  18750. };
  18751. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18752. /**
  18753. * Gets the world distance between the min and max points of the bounding box
  18754. */
  18755. get: function () {
  18756. var boundingBox = this.boundingBox;
  18757. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18758. return size.length();
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18764. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18765. };
  18766. /** @hidden */
  18767. BoundingInfo.prototype._checkCollision = function (collider) {
  18768. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18769. };
  18770. BoundingInfo.prototype.intersectsPoint = function (point) {
  18771. if (!this.boundingSphere.centerWorld) {
  18772. return false;
  18773. }
  18774. if (!this.boundingSphere.intersectsPoint(point)) {
  18775. return false;
  18776. }
  18777. if (!this.boundingBox.intersectsPoint(point)) {
  18778. return false;
  18779. }
  18780. return true;
  18781. };
  18782. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18783. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18784. return false;
  18785. }
  18786. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18787. return false;
  18788. }
  18789. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18790. return false;
  18791. }
  18792. if (!precise) {
  18793. return true;
  18794. }
  18795. var box0 = this.boundingBox;
  18796. var box1 = boundingInfo.boundingBox;
  18797. if (!axisOverlap(box0.directions[0], box0, box1))
  18798. return false;
  18799. if (!axisOverlap(box0.directions[1], box0, box1))
  18800. return false;
  18801. if (!axisOverlap(box0.directions[2], box0, box1))
  18802. return false;
  18803. if (!axisOverlap(box1.directions[0], box0, box1))
  18804. return false;
  18805. if (!axisOverlap(box1.directions[1], box0, box1))
  18806. return false;
  18807. if (!axisOverlap(box1.directions[2], box0, box1))
  18808. return false;
  18809. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18810. return false;
  18811. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18812. return false;
  18813. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18814. return false;
  18815. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18816. return false;
  18817. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18818. return false;
  18819. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18820. return false;
  18821. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18822. return false;
  18823. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18824. return false;
  18825. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18826. return false;
  18827. return true;
  18828. };
  18829. return BoundingInfo;
  18830. }());
  18831. BABYLON.BoundingInfo = BoundingInfo;
  18832. })(BABYLON || (BABYLON = {}));
  18833. //# sourceMappingURL=babylon.boundingInfo.js.map
  18834. var BABYLON;
  18835. (function (BABYLON) {
  18836. var TransformNode = /** @class */ (function (_super) {
  18837. __extends(TransformNode, _super);
  18838. function TransformNode(name, scene, isPure) {
  18839. if (scene === void 0) { scene = null; }
  18840. if (isPure === void 0) { isPure = true; }
  18841. var _this = _super.call(this, name, scene) || this;
  18842. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18843. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18844. _this._up = new BABYLON.Vector3(0, 1, 0);
  18845. _this._right = new BABYLON.Vector3(1, 0, 0);
  18846. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18847. // Properties
  18848. _this._position = BABYLON.Vector3.Zero();
  18849. _this._rotation = BABYLON.Vector3.Zero();
  18850. _this._scaling = BABYLON.Vector3.One();
  18851. _this._isDirty = false;
  18852. /**
  18853. * Set the billboard mode. Default is 0.
  18854. *
  18855. * | Value | Type | Description |
  18856. * | --- | --- | --- |
  18857. * | 0 | BILLBOARDMODE_NONE | |
  18858. * | 1 | BILLBOARDMODE_X | |
  18859. * | 2 | BILLBOARDMODE_Y | |
  18860. * | 4 | BILLBOARDMODE_Z | |
  18861. * | 7 | BILLBOARDMODE_ALL | |
  18862. *
  18863. */
  18864. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18865. _this.scalingDeterminant = 1;
  18866. _this.infiniteDistance = false;
  18867. /**
  18868. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18869. * By default the system will update normals to compensate
  18870. */
  18871. _this.ignoreNonUniformScaling = false;
  18872. _this._localWorld = BABYLON.Matrix.Zero();
  18873. _this._absolutePosition = BABYLON.Vector3.Zero();
  18874. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18875. _this._postMultiplyPivotMatrix = false;
  18876. _this._isWorldMatrixFrozen = false;
  18877. /**
  18878. * An event triggered after the world matrix is updated
  18879. */
  18880. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18881. _this._nonUniformScaling = false;
  18882. if (isPure) {
  18883. _this.getScene().addTransformNode(_this);
  18884. }
  18885. return _this;
  18886. }
  18887. /**
  18888. * Gets a string identifying the name of the class
  18889. * @returns "TransformNode" string
  18890. */
  18891. TransformNode.prototype.getClassName = function () {
  18892. return "TransformNode";
  18893. };
  18894. Object.defineProperty(TransformNode.prototype, "position", {
  18895. /**
  18896. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18897. */
  18898. get: function () {
  18899. return this._position;
  18900. },
  18901. set: function (newPosition) {
  18902. this._position = newPosition;
  18903. this._isDirty = true;
  18904. },
  18905. enumerable: true,
  18906. configurable: true
  18907. });
  18908. Object.defineProperty(TransformNode.prototype, "rotation", {
  18909. /**
  18910. * 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)).
  18911. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18912. */
  18913. get: function () {
  18914. return this._rotation;
  18915. },
  18916. set: function (newRotation) {
  18917. this._rotation = newRotation;
  18918. this._isDirty = true;
  18919. },
  18920. enumerable: true,
  18921. configurable: true
  18922. });
  18923. Object.defineProperty(TransformNode.prototype, "scaling", {
  18924. /**
  18925. * 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)).
  18926. */
  18927. get: function () {
  18928. return this._scaling;
  18929. },
  18930. set: function (newScaling) {
  18931. this._scaling = newScaling;
  18932. this._isDirty = true;
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18938. /**
  18939. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18940. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18941. */
  18942. get: function () {
  18943. return this._rotationQuaternion;
  18944. },
  18945. set: function (quaternion) {
  18946. this._rotationQuaternion = quaternion;
  18947. //reset the rotation vector.
  18948. if (quaternion && this.rotation.length()) {
  18949. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18950. }
  18951. },
  18952. enumerable: true,
  18953. configurable: true
  18954. });
  18955. Object.defineProperty(TransformNode.prototype, "forward", {
  18956. /**
  18957. * The forward direction of that transform in world space.
  18958. */
  18959. get: function () {
  18960. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18961. },
  18962. enumerable: true,
  18963. configurable: true
  18964. });
  18965. Object.defineProperty(TransformNode.prototype, "up", {
  18966. /**
  18967. * The up direction of that transform in world space.
  18968. */
  18969. get: function () {
  18970. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Object.defineProperty(TransformNode.prototype, "right", {
  18976. /**
  18977. * The right direction of that transform in world space.
  18978. */
  18979. get: function () {
  18980. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18981. },
  18982. enumerable: true,
  18983. configurable: true
  18984. });
  18985. /**
  18986. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18987. * Returns the TransformNode.
  18988. */
  18989. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18990. this._poseMatrix.copyFrom(matrix);
  18991. return this;
  18992. };
  18993. /**
  18994. * Returns the mesh Pose matrix.
  18995. * Returned object : Matrix
  18996. */
  18997. TransformNode.prototype.getPoseMatrix = function () {
  18998. return this._poseMatrix;
  18999. };
  19000. /** @hidden */
  19001. TransformNode.prototype._isSynchronized = function () {
  19002. if (this._isDirty) {
  19003. return false;
  19004. }
  19005. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19006. return false;
  19007. if (this._cache.pivotMatrixUpdated) {
  19008. return false;
  19009. }
  19010. if (this.infiniteDistance) {
  19011. return false;
  19012. }
  19013. if (!this._cache.position.equals(this._position))
  19014. return false;
  19015. if (this._rotationQuaternion) {
  19016. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19017. return false;
  19018. }
  19019. if (!this._cache.rotation.equals(this._rotation))
  19020. return false;
  19021. if (!this._cache.scaling.equals(this._scaling))
  19022. return false;
  19023. return true;
  19024. };
  19025. /** @hidden */
  19026. TransformNode.prototype._initCache = function () {
  19027. _super.prototype._initCache.call(this);
  19028. this._cache.localMatrixUpdated = false;
  19029. this._cache.position = BABYLON.Vector3.Zero();
  19030. this._cache.scaling = BABYLON.Vector3.Zero();
  19031. this._cache.rotation = BABYLON.Vector3.Zero();
  19032. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19033. this._cache.billboardMode = -1;
  19034. };
  19035. TransformNode.prototype.markAsDirty = function (property) {
  19036. if (property === "rotation") {
  19037. this.rotationQuaternion = null;
  19038. }
  19039. this._currentRenderId = Number.MAX_VALUE;
  19040. this._isDirty = true;
  19041. return this;
  19042. };
  19043. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19044. /**
  19045. * Returns the current mesh absolute position.
  19046. * Returns a Vector3.
  19047. */
  19048. get: function () {
  19049. return this._absolutePosition;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. /**
  19055. * Sets a new matrix to apply before all other transformation
  19056. * @param matrix defines the transform matrix
  19057. * @returns the current TransformNode
  19058. */
  19059. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19060. return this.setPivotMatrix(matrix, false);
  19061. };
  19062. /**
  19063. * Sets a new pivot matrix to the current node
  19064. * @param matrix defines the new pivot matrix to use
  19065. * @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
  19066. * @returns the current TransformNode
  19067. */
  19068. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19069. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19070. this._pivotMatrix = matrix.clone();
  19071. this._cache.pivotMatrixUpdated = true;
  19072. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19073. if (this._postMultiplyPivotMatrix) {
  19074. if (!this._pivotMatrixInverse) {
  19075. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19076. }
  19077. else {
  19078. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19079. }
  19080. }
  19081. return this;
  19082. };
  19083. /**
  19084. * Returns the mesh pivot matrix.
  19085. * Default : Identity.
  19086. * A Matrix is returned.
  19087. */
  19088. TransformNode.prototype.getPivotMatrix = function () {
  19089. return this._pivotMatrix;
  19090. };
  19091. /**
  19092. * Prevents the World matrix to be computed any longer.
  19093. * Returns the TransformNode.
  19094. */
  19095. TransformNode.prototype.freezeWorldMatrix = function () {
  19096. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19097. this.computeWorldMatrix(true);
  19098. this._isWorldMatrixFrozen = true;
  19099. return this;
  19100. };
  19101. /**
  19102. * Allows back the World matrix computation.
  19103. * Returns the TransformNode.
  19104. */
  19105. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19106. this._isWorldMatrixFrozen = false;
  19107. this.computeWorldMatrix(true);
  19108. return this;
  19109. };
  19110. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19111. /**
  19112. * True if the World matrix has been frozen.
  19113. * Returns a boolean.
  19114. */
  19115. get: function () {
  19116. return this._isWorldMatrixFrozen;
  19117. },
  19118. enumerable: true,
  19119. configurable: true
  19120. });
  19121. /**
  19122. * Retuns the mesh absolute position in the World.
  19123. * Returns a Vector3.
  19124. */
  19125. TransformNode.prototype.getAbsolutePosition = function () {
  19126. this.computeWorldMatrix();
  19127. return this._absolutePosition;
  19128. };
  19129. /**
  19130. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19131. * Returns the TransformNode.
  19132. */
  19133. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19134. if (!absolutePosition) {
  19135. return this;
  19136. }
  19137. var absolutePositionX;
  19138. var absolutePositionY;
  19139. var absolutePositionZ;
  19140. if (absolutePosition.x === undefined) {
  19141. if (arguments.length < 3) {
  19142. return this;
  19143. }
  19144. absolutePositionX = arguments[0];
  19145. absolutePositionY = arguments[1];
  19146. absolutePositionZ = arguments[2];
  19147. }
  19148. else {
  19149. absolutePositionX = absolutePosition.x;
  19150. absolutePositionY = absolutePosition.y;
  19151. absolutePositionZ = absolutePosition.z;
  19152. }
  19153. if (this.parent) {
  19154. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19155. invertParentWorldMatrix.invert();
  19156. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19157. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19158. }
  19159. else {
  19160. this.position.x = absolutePositionX;
  19161. this.position.y = absolutePositionY;
  19162. this.position.z = absolutePositionZ;
  19163. }
  19164. return this;
  19165. };
  19166. /**
  19167. * Sets the mesh position in its local space.
  19168. * Returns the TransformNode.
  19169. */
  19170. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19171. this.computeWorldMatrix();
  19172. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19173. return this;
  19174. };
  19175. /**
  19176. * Returns the mesh position in the local space from the current World matrix values.
  19177. * Returns a new Vector3.
  19178. */
  19179. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19180. this.computeWorldMatrix();
  19181. var invLocalWorldMatrix = this._localWorld.clone();
  19182. invLocalWorldMatrix.invert();
  19183. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19184. };
  19185. /**
  19186. * Translates the mesh along the passed Vector3 in its local space.
  19187. * Returns the TransformNode.
  19188. */
  19189. TransformNode.prototype.locallyTranslate = function (vector3) {
  19190. this.computeWorldMatrix(true);
  19191. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19192. return this;
  19193. };
  19194. /**
  19195. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19196. * @param targetPoint the position (must be in same space as current mesh) to look at
  19197. * @param yawCor optional yaw (y-axis) correction in radians
  19198. * @param pitchCor optional pitch (x-axis) correction in radians
  19199. * @param rollCor optional roll (z-axis) correction in radians
  19200. * @param space the choosen space of the target
  19201. * @returns the TransformNode.
  19202. */
  19203. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19204. if (yawCor === void 0) { yawCor = 0; }
  19205. if (pitchCor === void 0) { pitchCor = 0; }
  19206. if (rollCor === void 0) { rollCor = 0; }
  19207. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19208. var dv = TransformNode._lookAtVectorCache;
  19209. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19210. targetPoint.subtractToRef(pos, dv);
  19211. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19212. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19213. var pitch = Math.atan2(dv.y, len);
  19214. if (this.rotationQuaternion) {
  19215. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19216. }
  19217. else {
  19218. this.rotation.x = pitch + pitchCor;
  19219. this.rotation.y = yaw + yawCor;
  19220. this.rotation.z = rollCor;
  19221. }
  19222. return this;
  19223. };
  19224. /**
  19225. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19226. * This Vector3 is expressed in the World space.
  19227. */
  19228. TransformNode.prototype.getDirection = function (localAxis) {
  19229. var result = BABYLON.Vector3.Zero();
  19230. this.getDirectionToRef(localAxis, result);
  19231. return result;
  19232. };
  19233. /**
  19234. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19235. * localAxis is expressed in the mesh local space.
  19236. * result is computed in the Wordl space from the mesh World matrix.
  19237. * Returns the TransformNode.
  19238. */
  19239. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19240. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19241. return this;
  19242. };
  19243. /**
  19244. * Sets a new pivot point to the current node
  19245. * @param point defines the new pivot point to use
  19246. * @param space defines if the point is in world or local space (local by default)
  19247. * @returns the current TransformNode
  19248. */
  19249. TransformNode.prototype.setPivotPoint = function (point, space) {
  19250. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19251. if (this.getScene().getRenderId() == 0) {
  19252. this.computeWorldMatrix(true);
  19253. }
  19254. var wm = this.getWorldMatrix();
  19255. if (space == BABYLON.Space.WORLD) {
  19256. var tmat = BABYLON.Tmp.Matrix[0];
  19257. wm.invertToRef(tmat);
  19258. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19259. }
  19260. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19261. };
  19262. /**
  19263. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19264. */
  19265. TransformNode.prototype.getPivotPoint = function () {
  19266. var point = BABYLON.Vector3.Zero();
  19267. this.getPivotPointToRef(point);
  19268. return point;
  19269. };
  19270. /**
  19271. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19272. * Returns the TransformNode.
  19273. */
  19274. TransformNode.prototype.getPivotPointToRef = function (result) {
  19275. result.x = -this._pivotMatrix.m[12];
  19276. result.y = -this._pivotMatrix.m[13];
  19277. result.z = -this._pivotMatrix.m[14];
  19278. return this;
  19279. };
  19280. /**
  19281. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19282. */
  19283. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19284. var point = BABYLON.Vector3.Zero();
  19285. this.getAbsolutePivotPointToRef(point);
  19286. return point;
  19287. };
  19288. /**
  19289. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19290. * Returns the TransformNode.
  19291. */
  19292. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19293. result.x = this._pivotMatrix.m[12];
  19294. result.y = this._pivotMatrix.m[13];
  19295. result.z = this._pivotMatrix.m[14];
  19296. this.getPivotPointToRef(result);
  19297. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19298. return this;
  19299. };
  19300. /**
  19301. * Defines the passed node as the parent of the current node.
  19302. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19303. * Returns the TransformNode.
  19304. */
  19305. TransformNode.prototype.setParent = function (node) {
  19306. if (!node && !this.parent) {
  19307. return this;
  19308. }
  19309. if (!node) {
  19310. var rotation = BABYLON.Tmp.Quaternion[0];
  19311. var position = BABYLON.Tmp.Vector3[0];
  19312. var scale = BABYLON.Tmp.Vector3[1];
  19313. if (this.parent && this.parent.computeWorldMatrix) {
  19314. this.parent.computeWorldMatrix(true);
  19315. }
  19316. this.computeWorldMatrix(true);
  19317. this.getWorldMatrix().decompose(scale, rotation, position);
  19318. if (this.rotationQuaternion) {
  19319. this.rotationQuaternion.copyFrom(rotation);
  19320. }
  19321. else {
  19322. rotation.toEulerAnglesToRef(this.rotation);
  19323. }
  19324. this.scaling.x = scale.x;
  19325. this.scaling.y = scale.y;
  19326. this.scaling.z = scale.z;
  19327. this.position.x = position.x;
  19328. this.position.y = position.y;
  19329. this.position.z = position.z;
  19330. }
  19331. else {
  19332. var rotation = BABYLON.Tmp.Quaternion[0];
  19333. var position = BABYLON.Tmp.Vector3[0];
  19334. var scale = BABYLON.Tmp.Vector3[1];
  19335. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19336. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19337. this.computeWorldMatrix(true);
  19338. node.computeWorldMatrix(true);
  19339. node.getWorldMatrix().invertToRef(invParentMatrix);
  19340. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19341. diffMatrix.decompose(scale, rotation, position);
  19342. if (this.rotationQuaternion) {
  19343. this.rotationQuaternion.copyFrom(rotation);
  19344. }
  19345. else {
  19346. rotation.toEulerAnglesToRef(this.rotation);
  19347. }
  19348. this.position.x = position.x;
  19349. this.position.y = position.y;
  19350. this.position.z = position.z;
  19351. this.scaling.x = scale.x;
  19352. this.scaling.y = scale.y;
  19353. this.scaling.z = scale.z;
  19354. }
  19355. this.parent = node;
  19356. return this;
  19357. };
  19358. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19359. get: function () {
  19360. return this._nonUniformScaling;
  19361. },
  19362. enumerable: true,
  19363. configurable: true
  19364. });
  19365. /** @hidden */
  19366. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19367. if (this._nonUniformScaling === value) {
  19368. return false;
  19369. }
  19370. this._nonUniformScaling = value;
  19371. return true;
  19372. };
  19373. /**
  19374. * Attach the current TransformNode to another TransformNode associated with a bone
  19375. * @param bone Bone affecting the TransformNode
  19376. * @param affectedTransformNode TransformNode associated with the bone
  19377. */
  19378. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19379. this._transformToBoneReferal = affectedTransformNode;
  19380. this.parent = bone;
  19381. if (bone.getWorldMatrix().determinant() < 0) {
  19382. this.scalingDeterminant *= -1;
  19383. }
  19384. return this;
  19385. };
  19386. TransformNode.prototype.detachFromBone = function () {
  19387. if (!this.parent) {
  19388. return this;
  19389. }
  19390. if (this.parent.getWorldMatrix().determinant() < 0) {
  19391. this.scalingDeterminant *= -1;
  19392. }
  19393. this._transformToBoneReferal = null;
  19394. this.parent = null;
  19395. return this;
  19396. };
  19397. /**
  19398. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19399. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19400. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19401. * The passed axis is also normalized.
  19402. * Returns the TransformNode.
  19403. */
  19404. TransformNode.prototype.rotate = function (axis, amount, space) {
  19405. axis.normalize();
  19406. if (!this.rotationQuaternion) {
  19407. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19408. this.rotation = BABYLON.Vector3.Zero();
  19409. }
  19410. var rotationQuaternion;
  19411. if (!space || space === BABYLON.Space.LOCAL) {
  19412. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19413. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19414. }
  19415. else {
  19416. if (this.parent) {
  19417. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19418. invertParentWorldMatrix.invert();
  19419. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19420. }
  19421. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19422. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19423. }
  19424. return this;
  19425. };
  19426. /**
  19427. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19428. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19429. * The passed axis is also normalized.
  19430. * Returns the TransformNode.
  19431. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19432. */
  19433. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19434. axis.normalize();
  19435. if (!this.rotationQuaternion) {
  19436. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19437. this.rotation.copyFromFloats(0, 0, 0);
  19438. }
  19439. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19440. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19441. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19442. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19443. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19444. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19445. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19446. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19447. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19448. return this;
  19449. };
  19450. /**
  19451. * Translates the mesh along the axis vector for the passed distance in the given space.
  19452. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19453. * Returns the TransformNode.
  19454. */
  19455. TransformNode.prototype.translate = function (axis, distance, space) {
  19456. var displacementVector = axis.scale(distance);
  19457. if (!space || space === BABYLON.Space.LOCAL) {
  19458. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19459. this.setPositionWithLocalVector(tempV3);
  19460. }
  19461. else {
  19462. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19463. }
  19464. return this;
  19465. };
  19466. /**
  19467. * Adds a rotation step to the mesh current rotation.
  19468. * x, y, z are Euler angles expressed in radians.
  19469. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19470. * This means this rotation is made in the mesh local space only.
  19471. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19472. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19473. * ```javascript
  19474. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19475. * ```
  19476. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19477. * 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.
  19478. * Returns the TransformNode.
  19479. */
  19480. TransformNode.prototype.addRotation = function (x, y, z) {
  19481. var rotationQuaternion;
  19482. if (this.rotationQuaternion) {
  19483. rotationQuaternion = this.rotationQuaternion;
  19484. }
  19485. else {
  19486. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19487. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19488. }
  19489. var accumulation = BABYLON.Tmp.Quaternion[0];
  19490. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19491. rotationQuaternion.multiplyInPlace(accumulation);
  19492. if (!this.rotationQuaternion) {
  19493. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19494. }
  19495. return this;
  19496. };
  19497. /**
  19498. * Computes the world matrix of the node
  19499. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19500. * @returns the world matrix
  19501. */
  19502. TransformNode.prototype.computeWorldMatrix = function (force) {
  19503. if (this._isWorldMatrixFrozen) {
  19504. return this._worldMatrix;
  19505. }
  19506. if (!force && this.isSynchronized()) {
  19507. this._currentRenderId = this.getScene().getRenderId();
  19508. return this._worldMatrix;
  19509. }
  19510. this._updateCache();
  19511. this._cache.position.copyFrom(this.position);
  19512. this._cache.scaling.copyFrom(this.scaling);
  19513. this._cache.pivotMatrixUpdated = false;
  19514. this._cache.billboardMode = this.billboardMode;
  19515. this._currentRenderId = this.getScene().getRenderId();
  19516. this._childRenderId = this.getScene().getRenderId();
  19517. this._isDirty = false;
  19518. // Scaling
  19519. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19520. // Rotation
  19521. //rotate, if quaternion is set and rotation was used
  19522. if (this.rotationQuaternion) {
  19523. var len = this.rotation.length();
  19524. if (len) {
  19525. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19526. this.rotation.copyFromFloats(0, 0, 0);
  19527. }
  19528. }
  19529. if (this.rotationQuaternion) {
  19530. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19531. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19532. }
  19533. else {
  19534. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19535. this._cache.rotation.copyFrom(this.rotation);
  19536. }
  19537. // Translation
  19538. var camera = this.getScene().activeCamera;
  19539. if (this.infiniteDistance && !this.parent && camera) {
  19540. var cameraWorldMatrix = camera.getWorldMatrix();
  19541. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19542. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19543. }
  19544. else {
  19545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19546. }
  19547. // Composing transformations
  19548. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19549. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19550. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19551. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19552. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19553. // Need to decompose each rotation here
  19554. var currentPosition = BABYLON.Tmp.Vector3[3];
  19555. if (this.parent && this.parent.getWorldMatrix) {
  19556. if (this._transformToBoneReferal) {
  19557. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19558. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19559. }
  19560. else {
  19561. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19562. }
  19563. }
  19564. else {
  19565. currentPosition.copyFrom(this.position);
  19566. }
  19567. currentPosition.subtractInPlace(camera.globalPosition);
  19568. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19569. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19570. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19571. }
  19572. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19573. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19574. }
  19575. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19576. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19577. }
  19578. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19579. }
  19580. else {
  19581. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19582. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19583. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19584. }
  19585. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19586. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19587. }
  19588. // Post multiply inverse of pivotMatrix
  19589. if (this._postMultiplyPivotMatrix) {
  19590. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19591. }
  19592. // Local world
  19593. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19594. // Parent
  19595. if (this.parent && this.parent.getWorldMatrix) {
  19596. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19597. if (this._transformToBoneReferal) {
  19598. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19599. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19600. }
  19601. else {
  19602. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19603. }
  19604. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19605. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19606. this._worldMatrix.copyFrom(this._localWorld);
  19607. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19608. }
  19609. else {
  19610. if (this._transformToBoneReferal) {
  19611. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19612. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19613. }
  19614. else {
  19615. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19616. }
  19617. }
  19618. this._markSyncedWithParent();
  19619. }
  19620. else {
  19621. this._worldMatrix.copyFrom(this._localWorld);
  19622. }
  19623. // Normal matrix
  19624. if (!this.ignoreNonUniformScaling) {
  19625. if (this.scaling.isNonUniform) {
  19626. this._updateNonUniformScalingState(true);
  19627. }
  19628. else if (this.parent && this.parent._nonUniformScaling) {
  19629. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19630. }
  19631. else {
  19632. this._updateNonUniformScalingState(false);
  19633. }
  19634. }
  19635. else {
  19636. this._updateNonUniformScalingState(false);
  19637. }
  19638. this._afterComputeWorldMatrix();
  19639. // Absolute position
  19640. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19641. // Callbacks
  19642. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19643. if (!this._poseMatrix) {
  19644. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19645. }
  19646. // Cache the determinant
  19647. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19648. return this._worldMatrix;
  19649. };
  19650. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19651. };
  19652. /**
  19653. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19654. * @param func: callback function to add
  19655. *
  19656. * Returns the TransformNode.
  19657. */
  19658. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19659. this.onAfterWorldMatrixUpdateObservable.add(func);
  19660. return this;
  19661. };
  19662. /**
  19663. * Removes a registered callback function.
  19664. * Returns the TransformNode.
  19665. */
  19666. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19667. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19668. return this;
  19669. };
  19670. /**
  19671. * Clone the current transform node
  19672. * Returns the new transform node
  19673. * @param name Name of the new clone
  19674. * @param newParent New parent for the clone
  19675. * @param doNotCloneChildren Do not clone children hierarchy
  19676. */
  19677. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19678. var _this = this;
  19679. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19680. result.name = name;
  19681. result.id = name;
  19682. if (newParent) {
  19683. result.parent = newParent;
  19684. }
  19685. if (!doNotCloneChildren) {
  19686. // Children
  19687. var directDescendants = this.getDescendants(true);
  19688. for (var index = 0; index < directDescendants.length; index++) {
  19689. var child = directDescendants[index];
  19690. if (child.clone) {
  19691. child.clone(name + "." + child.name, result);
  19692. }
  19693. }
  19694. }
  19695. return result;
  19696. };
  19697. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19698. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19699. serializationObject.type = this.getClassName();
  19700. // Parent
  19701. if (this.parent) {
  19702. serializationObject.parentId = this.parent.id;
  19703. }
  19704. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19705. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19706. }
  19707. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19708. serializationObject.isEnabled = this.isEnabled();
  19709. // Parent
  19710. if (this.parent) {
  19711. serializationObject.parentId = this.parent.id;
  19712. }
  19713. return serializationObject;
  19714. };
  19715. // Statics
  19716. /**
  19717. * Returns a new TransformNode object parsed from the source provided.
  19718. * The parameter `parsedMesh` is the source.
  19719. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19720. */
  19721. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19722. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19723. if (BABYLON.Tags) {
  19724. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19725. }
  19726. if (parsedTransformNode.localMatrix) {
  19727. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19728. }
  19729. else if (parsedTransformNode.pivotMatrix) {
  19730. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19731. }
  19732. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19733. // Parent
  19734. if (parsedTransformNode.parentId) {
  19735. transformNode._waitingParentId = parsedTransformNode.parentId;
  19736. }
  19737. return transformNode;
  19738. };
  19739. /**
  19740. * Releases resources associated with this transform node.
  19741. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19742. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19743. */
  19744. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19745. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19746. // Animations
  19747. this.getScene().stopAnimation(this);
  19748. // Remove from scene
  19749. this.getScene().removeTransformNode(this);
  19750. this.onAfterWorldMatrixUpdateObservable.clear();
  19751. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19752. };
  19753. // Statics
  19754. TransformNode.BILLBOARDMODE_NONE = 0;
  19755. TransformNode.BILLBOARDMODE_X = 1;
  19756. TransformNode.BILLBOARDMODE_Y = 2;
  19757. TransformNode.BILLBOARDMODE_Z = 4;
  19758. TransformNode.BILLBOARDMODE_ALL = 7;
  19759. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19760. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19761. __decorate([
  19762. BABYLON.serializeAsVector3("position")
  19763. ], TransformNode.prototype, "_position", void 0);
  19764. __decorate([
  19765. BABYLON.serializeAsVector3("rotation")
  19766. ], TransformNode.prototype, "_rotation", void 0);
  19767. __decorate([
  19768. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19769. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19770. __decorate([
  19771. BABYLON.serializeAsVector3("scaling")
  19772. ], TransformNode.prototype, "_scaling", void 0);
  19773. __decorate([
  19774. BABYLON.serialize()
  19775. ], TransformNode.prototype, "billboardMode", void 0);
  19776. __decorate([
  19777. BABYLON.serialize()
  19778. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19779. __decorate([
  19780. BABYLON.serialize()
  19781. ], TransformNode.prototype, "infiniteDistance", void 0);
  19782. __decorate([
  19783. BABYLON.serialize()
  19784. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19785. return TransformNode;
  19786. }(BABYLON.Node));
  19787. BABYLON.TransformNode = TransformNode;
  19788. })(BABYLON || (BABYLON = {}));
  19789. //# sourceMappingURL=babylon.transformNode.js.map
  19790. var BABYLON;
  19791. (function (BABYLON) {
  19792. /**
  19793. * Class used to store all common mesh properties
  19794. */
  19795. var AbstractMesh = /** @class */ (function (_super) {
  19796. __extends(AbstractMesh, _super);
  19797. // Constructor
  19798. /**
  19799. * Creates a new AbstractMesh
  19800. * @param name defines the name of the mesh
  19801. * @param scene defines the hosting scene
  19802. */
  19803. function AbstractMesh(name, scene) {
  19804. if (scene === void 0) { scene = null; }
  19805. var _this = _super.call(this, name, scene, false) || this;
  19806. _this._facetNb = 0; // facet number
  19807. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19808. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19809. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19810. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19811. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19812. _this._subDiv = {
  19813. max: 1,
  19814. X: 1,
  19815. Y: 1,
  19816. Z: 1
  19817. };
  19818. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19819. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19820. /** Gets ot sets the culling strategy to use to find visible meshes */
  19821. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19822. // Events
  19823. /**
  19824. * An event triggered when this mesh collides with another one
  19825. */
  19826. _this.onCollideObservable = new BABYLON.Observable();
  19827. /**
  19828. * An event triggered when the collision's position changes
  19829. */
  19830. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19831. /**
  19832. * An event triggered when material is changed
  19833. */
  19834. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19835. // Properties
  19836. /**
  19837. * Gets or sets the orientation for POV movement & rotation
  19838. */
  19839. _this.definedFacingForward = true;
  19840. /**
  19841. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19842. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19843. * * 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.
  19844. * @see http://doc.babylonjs.com/features/occlusionquery
  19845. */
  19846. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19847. /**
  19848. * 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:
  19849. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19850. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19851. * * 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.
  19852. * @see http://doc.babylonjs.com/features/occlusionquery
  19853. */
  19854. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19855. /**
  19856. * 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.
  19857. * The default value is -1 which means don't break the query and wait till the result
  19858. * @see http://doc.babylonjs.com/features/occlusionquery
  19859. */
  19860. _this.occlusionRetryCount = -1;
  19861. /** @hidden */
  19862. _this._occlusionInternalRetryCounter = 0;
  19863. /** @hidden */
  19864. _this._isOccluded = false;
  19865. /** @hidden */
  19866. _this._isOcclusionQueryInProgress = false;
  19867. _this._visibility = 1.0;
  19868. /** Gets or sets the alpha index used to sort transparent meshes
  19869. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19870. */
  19871. _this.alphaIndex = Number.MAX_VALUE;
  19872. /**
  19873. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19874. */
  19875. _this.isVisible = true;
  19876. /**
  19877. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19878. */
  19879. _this.isPickable = true;
  19880. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19881. _this.showSubMeshesBoundingBox = false;
  19882. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19883. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19884. */
  19885. _this.isBlocker = false;
  19886. /**
  19887. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19888. */
  19889. _this.enablePointerMoveEvents = false;
  19890. /**
  19891. * Specifies the rendering group id for this mesh (0 by default)
  19892. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19893. */
  19894. _this.renderingGroupId = 0;
  19895. _this._receiveShadows = false;
  19896. /** Defines color to use when rendering outline */
  19897. _this.outlineColor = BABYLON.Color3.Red();
  19898. /** Define width to use when rendering outline */
  19899. _this.outlineWidth = 0.02;
  19900. /** Defines color to use when rendering overlay */
  19901. _this.overlayColor = BABYLON.Color3.Red();
  19902. /** Defines alpha to use when rendering overlay */
  19903. _this.overlayAlpha = 0.5;
  19904. _this._hasVertexAlpha = false;
  19905. _this._useVertexColors = true;
  19906. _this._computeBonesUsingShaders = true;
  19907. _this._numBoneInfluencers = 4;
  19908. _this._applyFog = true;
  19909. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19910. _this.useOctreeForRenderingSelection = true;
  19911. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19912. _this.useOctreeForPicking = true;
  19913. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19914. _this.useOctreeForCollisions = true;
  19915. _this._layerMask = 0x0FFFFFFF;
  19916. /**
  19917. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19918. */
  19919. _this.alwaysSelectAsActiveMesh = false;
  19920. /**
  19921. * Gets or sets the current action manager
  19922. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19923. */
  19924. _this.actionManager = null;
  19925. // Collisions
  19926. _this._checkCollisions = false;
  19927. _this._collisionMask = -1;
  19928. _this._collisionGroup = -1;
  19929. /**
  19930. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19931. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19932. */
  19933. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19934. /**
  19935. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19936. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19937. */
  19938. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19939. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19940. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19941. // Edges
  19942. /**
  19943. * Defines edge width used when edgesRenderer is enabled
  19944. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19945. */
  19946. _this.edgesWidth = 1;
  19947. /**
  19948. * Defines edge color used when edgesRenderer is enabled
  19949. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19950. */
  19951. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19952. // Cache
  19953. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19954. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19955. /** @hidden */
  19956. _this._renderId = 0;
  19957. /** @hidden */
  19958. _this._intersectionsInProgress = new Array();
  19959. /** @hidden */
  19960. _this._unIndexed = false;
  19961. /** @hidden */
  19962. _this._lightSources = new Array();
  19963. /**
  19964. * An event triggered when the mesh is rebuilt.
  19965. */
  19966. _this.onRebuildObservable = new BABYLON.Observable();
  19967. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19968. if (collidedMesh === void 0) { collidedMesh = null; }
  19969. //TODO move this to the collision coordinator!
  19970. if (_this.getScene().workerCollisions)
  19971. newPosition.multiplyInPlace(_this._collider._radius);
  19972. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19973. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19974. _this.position.addInPlace(_this._diffPositionForCollisions);
  19975. }
  19976. if (collidedMesh) {
  19977. _this.onCollideObservable.notifyObservers(collidedMesh);
  19978. }
  19979. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19980. };
  19981. _this.getScene().addMesh(_this);
  19982. _this._resyncLightSources();
  19983. return _this;
  19984. }
  19985. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19986. /**
  19987. * No billboard
  19988. */
  19989. get: function () {
  19990. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19991. },
  19992. enumerable: true,
  19993. configurable: true
  19994. });
  19995. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19996. /** Billboard on X axis */
  19997. get: function () {
  19998. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20004. /** Billboard on Y axis */
  20005. get: function () {
  20006. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20012. /** Billboard on Z axis */
  20013. get: function () {
  20014. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20020. /** Billboard on all axes */
  20021. get: function () {
  20022. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20028. /**
  20029. * Gets the number of facets in the mesh
  20030. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20031. */
  20032. get: function () {
  20033. return this._facetNb;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20039. /**
  20040. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20041. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20042. */
  20043. get: function () {
  20044. return this._partitioningSubdivisions;
  20045. },
  20046. set: function (nb) {
  20047. this._partitioningSubdivisions = nb;
  20048. },
  20049. enumerable: true,
  20050. configurable: true
  20051. });
  20052. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20053. /**
  20054. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20055. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20056. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20057. */
  20058. get: function () {
  20059. return this._partitioningBBoxRatio;
  20060. },
  20061. set: function (ratio) {
  20062. this._partitioningBBoxRatio = ratio;
  20063. },
  20064. enumerable: true,
  20065. configurable: true
  20066. });
  20067. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20068. /**
  20069. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20070. * Works only for updatable meshes.
  20071. * Doesn't work with multi-materials
  20072. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20073. */
  20074. get: function () {
  20075. return this._facetDepthSort;
  20076. },
  20077. set: function (sort) {
  20078. this._facetDepthSort = sort;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20084. /**
  20085. * The location (Vector3) where the facet depth sort must be computed from.
  20086. * By default, the active camera position.
  20087. * Used only when facet depth sort is enabled
  20088. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20089. */
  20090. get: function () {
  20091. return this._facetDepthSortFrom;
  20092. },
  20093. set: function (location) {
  20094. this._facetDepthSortFrom = location;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20100. /**
  20101. * gets a boolean indicating if facetData is enabled
  20102. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20103. */
  20104. get: function () {
  20105. return this._facetDataEnabled;
  20106. },
  20107. enumerable: true,
  20108. configurable: true
  20109. });
  20110. /** @hidden */
  20111. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20112. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20113. return false;
  20114. }
  20115. this._markSubMeshesAsMiscDirty();
  20116. return true;
  20117. };
  20118. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20119. /** Set a function to call when this mesh collides with another one */
  20120. set: function (callback) {
  20121. if (this._onCollideObserver) {
  20122. this.onCollideObservable.remove(this._onCollideObserver);
  20123. }
  20124. this._onCollideObserver = this.onCollideObservable.add(callback);
  20125. },
  20126. enumerable: true,
  20127. configurable: true
  20128. });
  20129. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20130. /** Set a function to call when the collision's position changes */
  20131. set: function (callback) {
  20132. if (this._onCollisionPositionChangeObserver) {
  20133. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20134. }
  20135. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20141. /**
  20142. * 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
  20143. * @see http://doc.babylonjs.com/features/occlusionquery
  20144. */
  20145. get: function () {
  20146. return this._isOccluded;
  20147. },
  20148. set: function (value) {
  20149. this._isOccluded = value;
  20150. },
  20151. enumerable: true,
  20152. configurable: true
  20153. });
  20154. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20155. /**
  20156. * Flag to check the progress status of the query
  20157. * @see http://doc.babylonjs.com/features/occlusionquery
  20158. */
  20159. get: function () {
  20160. return this._isOcclusionQueryInProgress;
  20161. },
  20162. enumerable: true,
  20163. configurable: true
  20164. });
  20165. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20166. /**
  20167. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20168. */
  20169. get: function () {
  20170. return this._visibility;
  20171. },
  20172. /**
  20173. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20174. */
  20175. set: function (value) {
  20176. if (this._visibility === value) {
  20177. return;
  20178. }
  20179. this._visibility = value;
  20180. this._markSubMeshesAsMiscDirty();
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. Object.defineProperty(AbstractMesh.prototype, "material", {
  20186. /** Gets or sets current material */
  20187. get: function () {
  20188. return this._material;
  20189. },
  20190. set: function (value) {
  20191. if (this._material === value) {
  20192. return;
  20193. }
  20194. this._material = value;
  20195. if (this.onMaterialChangedObservable.hasObservers) {
  20196. this.onMaterialChangedObservable.notifyObservers(this);
  20197. }
  20198. if (!this.subMeshes) {
  20199. return;
  20200. }
  20201. this._unBindEffect();
  20202. },
  20203. enumerable: true,
  20204. configurable: true
  20205. });
  20206. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20207. /**
  20208. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20209. * @see http://doc.babylonjs.com/babylon101/shadows
  20210. */
  20211. get: function () {
  20212. return this._receiveShadows;
  20213. },
  20214. set: function (value) {
  20215. if (this._receiveShadows === value) {
  20216. return;
  20217. }
  20218. this._receiveShadows = value;
  20219. this._markSubMeshesAsLightDirty();
  20220. },
  20221. enumerable: true,
  20222. configurable: true
  20223. });
  20224. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20225. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20226. get: function () {
  20227. return this._hasVertexAlpha;
  20228. },
  20229. set: function (value) {
  20230. if (this._hasVertexAlpha === value) {
  20231. return;
  20232. }
  20233. this._hasVertexAlpha = value;
  20234. this._markSubMeshesAsAttributesDirty();
  20235. this._markSubMeshesAsMiscDirty();
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20241. /** 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) */
  20242. get: function () {
  20243. return this._useVertexColors;
  20244. },
  20245. set: function (value) {
  20246. if (this._useVertexColors === value) {
  20247. return;
  20248. }
  20249. this._useVertexColors = value;
  20250. this._markSubMeshesAsAttributesDirty();
  20251. },
  20252. enumerable: true,
  20253. configurable: true
  20254. });
  20255. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20256. /**
  20257. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20258. */
  20259. get: function () {
  20260. return this._computeBonesUsingShaders;
  20261. },
  20262. set: function (value) {
  20263. if (this._computeBonesUsingShaders === value) {
  20264. return;
  20265. }
  20266. this._computeBonesUsingShaders = value;
  20267. this._markSubMeshesAsAttributesDirty();
  20268. },
  20269. enumerable: true,
  20270. configurable: true
  20271. });
  20272. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20273. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20274. get: function () {
  20275. return this._numBoneInfluencers;
  20276. },
  20277. set: function (value) {
  20278. if (this._numBoneInfluencers === value) {
  20279. return;
  20280. }
  20281. this._numBoneInfluencers = value;
  20282. this._markSubMeshesAsAttributesDirty();
  20283. },
  20284. enumerable: true,
  20285. configurable: true
  20286. });
  20287. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20288. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20289. get: function () {
  20290. return this._applyFog;
  20291. },
  20292. set: function (value) {
  20293. if (this._applyFog === value) {
  20294. return;
  20295. }
  20296. this._applyFog = value;
  20297. this._markSubMeshesAsMiscDirty();
  20298. },
  20299. enumerable: true,
  20300. configurable: true
  20301. });
  20302. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20303. /**
  20304. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20305. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20306. */
  20307. get: function () {
  20308. return this._layerMask;
  20309. },
  20310. set: function (value) {
  20311. if (value === this._layerMask) {
  20312. return;
  20313. }
  20314. this._layerMask = value;
  20315. this._resyncLightSources();
  20316. },
  20317. enumerable: true,
  20318. configurable: true
  20319. });
  20320. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20321. /**
  20322. * Gets or sets a collision mask used to mask collisions (default is -1).
  20323. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20324. */
  20325. get: function () {
  20326. return this._collisionMask;
  20327. },
  20328. set: function (mask) {
  20329. this._collisionMask = !isNaN(mask) ? mask : -1;
  20330. },
  20331. enumerable: true,
  20332. configurable: true
  20333. });
  20334. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20335. /**
  20336. * Gets or sets the current collision group mask (-1 by default).
  20337. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20338. */
  20339. get: function () {
  20340. return this._collisionGroup;
  20341. },
  20342. set: function (mask) {
  20343. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20344. },
  20345. enumerable: true,
  20346. configurable: true
  20347. });
  20348. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20349. /** @hidden */
  20350. get: function () {
  20351. return null;
  20352. },
  20353. enumerable: true,
  20354. configurable: true
  20355. });
  20356. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20357. get: function () {
  20358. return this._skeleton;
  20359. },
  20360. /**
  20361. * Gets or sets a skeleton to apply skining transformations
  20362. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20363. */
  20364. set: function (value) {
  20365. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20366. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20367. }
  20368. if (value && value.needInitialSkinMatrix) {
  20369. value._registerMeshWithPoseMatrix(this);
  20370. }
  20371. this._skeleton = value;
  20372. if (!this._skeleton) {
  20373. this._bonesTransformMatrices = null;
  20374. }
  20375. this._markSubMeshesAsAttributesDirty();
  20376. },
  20377. enumerable: true,
  20378. configurable: true
  20379. });
  20380. /**
  20381. * Returns the string "AbstractMesh"
  20382. * @returns "AbstractMesh"
  20383. */
  20384. AbstractMesh.prototype.getClassName = function () {
  20385. return "AbstractMesh";
  20386. };
  20387. /**
  20388. * Gets a string representation of the current mesh
  20389. * @param fullDetails defines a boolean indicating if full details must be included
  20390. * @returns a string representation of the current mesh
  20391. */
  20392. AbstractMesh.prototype.toString = function (fullDetails) {
  20393. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20394. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20395. if (this._skeleton) {
  20396. ret += ", skeleton: " + this._skeleton.name;
  20397. }
  20398. if (fullDetails) {
  20399. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20400. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20401. }
  20402. return ret;
  20403. };
  20404. /** @hidden */
  20405. AbstractMesh.prototype._rebuild = function () {
  20406. this.onRebuildObservable.notifyObservers(this);
  20407. if (this._occlusionQuery) {
  20408. this._occlusionQuery = null;
  20409. }
  20410. if (!this.subMeshes) {
  20411. return;
  20412. }
  20413. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20414. var subMesh = _a[_i];
  20415. subMesh._rebuild();
  20416. }
  20417. };
  20418. /** @hidden */
  20419. AbstractMesh.prototype._resyncLightSources = function () {
  20420. this._lightSources.length = 0;
  20421. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20422. var light = _a[_i];
  20423. if (!light.isEnabled()) {
  20424. continue;
  20425. }
  20426. if (light.canAffectMesh(this)) {
  20427. this._lightSources.push(light);
  20428. }
  20429. }
  20430. this._markSubMeshesAsLightDirty();
  20431. };
  20432. /** @hidden */
  20433. AbstractMesh.prototype._resyncLighSource = function (light) {
  20434. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20435. var index = this._lightSources.indexOf(light);
  20436. if (index === -1) {
  20437. if (!isIn) {
  20438. return;
  20439. }
  20440. this._lightSources.push(light);
  20441. }
  20442. else {
  20443. if (isIn) {
  20444. return;
  20445. }
  20446. this._lightSources.splice(index, 1);
  20447. }
  20448. this._markSubMeshesAsLightDirty();
  20449. };
  20450. /** @hidden */
  20451. AbstractMesh.prototype._unBindEffect = function () {
  20452. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20453. var subMesh = _a[_i];
  20454. subMesh.setEffect(null);
  20455. }
  20456. };
  20457. /** @hidden */
  20458. AbstractMesh.prototype._removeLightSource = function (light) {
  20459. var index = this._lightSources.indexOf(light);
  20460. if (index === -1) {
  20461. return;
  20462. }
  20463. this._lightSources.splice(index, 1);
  20464. this._markSubMeshesAsLightDirty();
  20465. };
  20466. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20467. if (!this.subMeshes) {
  20468. return;
  20469. }
  20470. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20471. var subMesh = _a[_i];
  20472. if (subMesh._materialDefines) {
  20473. func(subMesh._materialDefines);
  20474. }
  20475. }
  20476. };
  20477. /** @hidden */
  20478. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20479. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20480. };
  20481. /** @hidden */
  20482. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20483. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20484. };
  20485. /** @hidden */
  20486. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20487. if (!this.subMeshes) {
  20488. return;
  20489. }
  20490. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20491. var subMesh = _a[_i];
  20492. var material = subMesh.getMaterial();
  20493. if (material) {
  20494. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20495. }
  20496. }
  20497. };
  20498. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20499. /**
  20500. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20501. */
  20502. get: function () {
  20503. return this._scaling;
  20504. },
  20505. set: function (newScaling) {
  20506. this._scaling = newScaling;
  20507. if (this.physicsImpostor) {
  20508. this.physicsImpostor.forceUpdate();
  20509. }
  20510. },
  20511. enumerable: true,
  20512. configurable: true
  20513. });
  20514. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20515. // Methods
  20516. /**
  20517. * Returns true if the mesh is blocked. Implemented by child classes
  20518. */
  20519. get: function () {
  20520. return false;
  20521. },
  20522. enumerable: true,
  20523. configurable: true
  20524. });
  20525. /**
  20526. * Returns the mesh itself by default. Implemented by child classes
  20527. * @param camera defines the camera to use to pick the right LOD level
  20528. * @returns the currentAbstractMesh
  20529. */
  20530. AbstractMesh.prototype.getLOD = function (camera) {
  20531. return this;
  20532. };
  20533. /**
  20534. * Returns 0 by default. Implemented by child classes
  20535. * @returns an integer
  20536. */
  20537. AbstractMesh.prototype.getTotalVertices = function () {
  20538. return 0;
  20539. };
  20540. /**
  20541. * Returns null by default. Implemented by child classes
  20542. * @returns null
  20543. */
  20544. AbstractMesh.prototype.getIndices = function () {
  20545. return null;
  20546. };
  20547. /**
  20548. * Returns the array of the requested vertex data kind. Implemented by child classes
  20549. * @param kind defines the vertex data kind to use
  20550. * @returns null
  20551. */
  20552. AbstractMesh.prototype.getVerticesData = function (kind) {
  20553. return null;
  20554. };
  20555. /**
  20556. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20557. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20558. * Note that a new underlying VertexBuffer object is created each call.
  20559. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20560. * @param kind defines vertex data kind:
  20561. * * BABYLON.VertexBuffer.PositionKind
  20562. * * BABYLON.VertexBuffer.UVKind
  20563. * * BABYLON.VertexBuffer.UV2Kind
  20564. * * BABYLON.VertexBuffer.UV3Kind
  20565. * * BABYLON.VertexBuffer.UV4Kind
  20566. * * BABYLON.VertexBuffer.UV5Kind
  20567. * * BABYLON.VertexBuffer.UV6Kind
  20568. * * BABYLON.VertexBuffer.ColorKind
  20569. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20570. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20571. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20572. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20573. * @param data defines the data source
  20574. * @param updatable defines if the data must be flagged as updatable (or static)
  20575. * @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
  20576. * @returns the current mesh
  20577. */
  20578. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20579. return this;
  20580. };
  20581. /**
  20582. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20583. * If the mesh has no geometry, it is simply returned as it is.
  20584. * @param kind defines vertex data kind:
  20585. * * BABYLON.VertexBuffer.PositionKind
  20586. * * BABYLON.VertexBuffer.UVKind
  20587. * * BABYLON.VertexBuffer.UV2Kind
  20588. * * BABYLON.VertexBuffer.UV3Kind
  20589. * * BABYLON.VertexBuffer.UV4Kind
  20590. * * BABYLON.VertexBuffer.UV5Kind
  20591. * * BABYLON.VertexBuffer.UV6Kind
  20592. * * BABYLON.VertexBuffer.ColorKind
  20593. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20594. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20595. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20596. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20597. * @param data defines the data source
  20598. * @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
  20599. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20600. * @returns the current mesh
  20601. */
  20602. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20603. return this;
  20604. };
  20605. /**
  20606. * Sets the mesh indices,
  20607. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20608. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20609. * @param totalVertices Defines the total number of vertices
  20610. * @returns the current mesh
  20611. */
  20612. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20613. return this;
  20614. };
  20615. /**
  20616. * Gets a boolean indicating if specific vertex data is present
  20617. * @param kind defines the vertex data kind to use
  20618. * @returns true is data kind is present
  20619. */
  20620. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20621. return false;
  20622. };
  20623. /**
  20624. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20625. * @returns a BoundingInfo
  20626. */
  20627. AbstractMesh.prototype.getBoundingInfo = function () {
  20628. if (this._masterMesh) {
  20629. return this._masterMesh.getBoundingInfo();
  20630. }
  20631. if (!this._boundingInfo) {
  20632. // this._boundingInfo is being created here
  20633. this._updateBoundingInfo();
  20634. }
  20635. // cannot be null.
  20636. return this._boundingInfo;
  20637. };
  20638. /**
  20639. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20640. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20641. * @returns the current mesh
  20642. */
  20643. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20644. if (includeDescendants === void 0) { includeDescendants = true; }
  20645. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20646. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20647. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20648. if (maxDimension === 0) {
  20649. return this;
  20650. }
  20651. var scale = 1 / maxDimension;
  20652. this.scaling.scaleInPlace(scale);
  20653. return this;
  20654. };
  20655. /**
  20656. * Overwrite the current bounding info
  20657. * @param boundingInfo defines the new bounding info
  20658. * @returns the current mesh
  20659. */
  20660. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20661. this._boundingInfo = boundingInfo;
  20662. return this;
  20663. };
  20664. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20665. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20666. get: function () {
  20667. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. /** @hidden */
  20673. AbstractMesh.prototype._preActivate = function () {
  20674. };
  20675. /** @hidden */
  20676. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20677. };
  20678. /** @hidden */
  20679. AbstractMesh.prototype._activate = function (renderId) {
  20680. this._renderId = renderId;
  20681. };
  20682. /**
  20683. * Gets the current world matrix
  20684. * @returns a Matrix
  20685. */
  20686. AbstractMesh.prototype.getWorldMatrix = function () {
  20687. if (this._masterMesh) {
  20688. return this._masterMesh.getWorldMatrix();
  20689. }
  20690. return _super.prototype.getWorldMatrix.call(this);
  20691. };
  20692. /** @hidden */
  20693. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20694. if (this._masterMesh) {
  20695. return this._masterMesh._getWorldMatrixDeterminant();
  20696. }
  20697. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20698. };
  20699. // ================================== Point of View Movement =================================
  20700. /**
  20701. * Perform relative position change from the point of view of behind the front of the mesh.
  20702. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20703. * Supports definition of mesh facing forward or backward
  20704. * @param amountRight defines the distance on the right axis
  20705. * @param amountUp defines the distance on the up axis
  20706. * @param amountForward defines the distance on the forward axis
  20707. * @returns the current mesh
  20708. */
  20709. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20710. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20711. return this;
  20712. };
  20713. /**
  20714. * Calculate relative position change from the point of view of behind the front of the mesh.
  20715. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20716. * Supports definition of mesh facing forward or backward
  20717. * @param amountRight defines the distance on the right axis
  20718. * @param amountUp defines the distance on the up axis
  20719. * @param amountForward defines the distance on the forward axis
  20720. * @returns the new displacement vector
  20721. */
  20722. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20723. var rotMatrix = new BABYLON.Matrix();
  20724. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20725. rotQuaternion.toRotationMatrix(rotMatrix);
  20726. var translationDelta = BABYLON.Vector3.Zero();
  20727. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20728. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20729. return translationDelta;
  20730. };
  20731. // ================================== Point of View Rotation =================================
  20732. /**
  20733. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20734. * Supports definition of mesh facing forward or backward
  20735. * @param flipBack defines the flip
  20736. * @param twirlClockwise defines the twirl
  20737. * @param tiltRight defines the tilt
  20738. * @returns the current mesh
  20739. */
  20740. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20741. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20742. return this;
  20743. };
  20744. /**
  20745. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20746. * Supports definition of mesh facing forward or backward.
  20747. * @param flipBack defines the flip
  20748. * @param twirlClockwise defines the twirl
  20749. * @param tiltRight defines the tilt
  20750. * @returns the new rotation vector
  20751. */
  20752. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20753. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20754. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20755. };
  20756. /**
  20757. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20758. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20759. * @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
  20760. * @returns the new bounding vectors
  20761. */
  20762. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20763. if (includeDescendants === void 0) { includeDescendants = true; }
  20764. if (predicate === void 0) { predicate = null; }
  20765. // Ensures that all world matrix will be recomputed.
  20766. this.getScene().incrementRenderId();
  20767. this.computeWorldMatrix(true);
  20768. var min;
  20769. var max;
  20770. var boundingInfo = this.getBoundingInfo();
  20771. if (!this.subMeshes) {
  20772. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20773. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20774. }
  20775. else {
  20776. min = boundingInfo.boundingBox.minimumWorld;
  20777. max = boundingInfo.boundingBox.maximumWorld;
  20778. }
  20779. if (includeDescendants) {
  20780. var descendants = this.getDescendants(false);
  20781. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20782. var descendant = descendants_1[_i];
  20783. var childMesh = descendant;
  20784. childMesh.computeWorldMatrix(true);
  20785. // Filters meshes based on custom predicate function.
  20786. if (predicate && !predicate(childMesh)) {
  20787. continue;
  20788. }
  20789. //make sure we have the needed params to get mix and max
  20790. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20791. continue;
  20792. }
  20793. var childBoundingInfo = childMesh.getBoundingInfo();
  20794. var boundingBox = childBoundingInfo.boundingBox;
  20795. var minBox = boundingBox.minimumWorld;
  20796. var maxBox = boundingBox.maximumWorld;
  20797. BABYLON.Tools.CheckExtends(minBox, min, max);
  20798. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20799. }
  20800. }
  20801. return {
  20802. min: min,
  20803. max: max
  20804. };
  20805. };
  20806. /** @hidden */
  20807. AbstractMesh.prototype._updateBoundingInfo = function () {
  20808. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20809. this._boundingInfo.update(this.worldMatrixFromCache);
  20810. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20811. return this;
  20812. };
  20813. /** @hidden */
  20814. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20815. if (!this.subMeshes) {
  20816. return this;
  20817. }
  20818. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20819. var subMesh = this.subMeshes[subIndex];
  20820. if (!subMesh.IsGlobal) {
  20821. subMesh.updateBoundingInfo(matrix);
  20822. }
  20823. }
  20824. return this;
  20825. };
  20826. /** @hidden */
  20827. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20828. // Bounding info
  20829. this._updateBoundingInfo();
  20830. };
  20831. /**
  20832. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20833. * A mesh is in the frustum if its bounding box intersects the frustum
  20834. * @param frustumPlanes defines the frustum to test
  20835. * @returns true if the mesh is in the frustum planes
  20836. */
  20837. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20838. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20839. };
  20840. /**
  20841. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20842. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20843. * @param frustumPlanes defines the frustum to test
  20844. * @returns true if the mesh is completely in the frustum planes
  20845. */
  20846. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20847. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20848. };
  20849. /**
  20850. * True if the mesh intersects another mesh or a SolidParticle object
  20851. * @param mesh defines a target mesh or SolidParticle to test
  20852. * @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)
  20853. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20854. * @returns true if there is an intersection
  20855. */
  20856. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20857. if (precise === void 0) { precise = false; }
  20858. if (!this._boundingInfo || !mesh._boundingInfo) {
  20859. return false;
  20860. }
  20861. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20862. return true;
  20863. }
  20864. if (includeDescendants) {
  20865. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20866. var child = _a[_i];
  20867. if (child.intersectsMesh(mesh, precise, true)) {
  20868. return true;
  20869. }
  20870. }
  20871. }
  20872. return false;
  20873. };
  20874. /**
  20875. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20876. * @param point defines the point to test
  20877. * @returns true if there is an intersection
  20878. */
  20879. AbstractMesh.prototype.intersectsPoint = function (point) {
  20880. if (!this._boundingInfo) {
  20881. return false;
  20882. }
  20883. return this._boundingInfo.intersectsPoint(point);
  20884. };
  20885. /**
  20886. * Gets the position of the current mesh in camera space
  20887. * @param camera defines the camera to use
  20888. * @returns a position
  20889. */
  20890. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20891. if (camera === void 0) { camera = null; }
  20892. if (!camera) {
  20893. camera = this.getScene().activeCamera;
  20894. }
  20895. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20896. };
  20897. /**
  20898. * Returns the distance from the mesh to the active camera
  20899. * @param camera defines the camera to use
  20900. * @returns the distance
  20901. */
  20902. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20903. if (camera === void 0) { camera = null; }
  20904. if (!camera) {
  20905. camera = this.getScene().activeCamera;
  20906. }
  20907. return this.absolutePosition.subtract(camera.position).length();
  20908. };
  20909. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20910. // Collisions
  20911. /**
  20912. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20913. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20914. */
  20915. get: function () {
  20916. return this._checkCollisions;
  20917. },
  20918. set: function (collisionEnabled) {
  20919. this._checkCollisions = collisionEnabled;
  20920. if (this.getScene().workerCollisions) {
  20921. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20922. }
  20923. },
  20924. enumerable: true,
  20925. configurable: true
  20926. });
  20927. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20928. /**
  20929. * Gets Collider object used to compute collisions (not physics)
  20930. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20931. */
  20932. get: function () {
  20933. return this._collider;
  20934. },
  20935. enumerable: true,
  20936. configurable: true
  20937. });
  20938. /**
  20939. * Move the mesh using collision engine
  20940. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20941. * @param displacement defines the requested displacement vector
  20942. * @returns the current mesh
  20943. */
  20944. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20945. var globalPosition = this.getAbsolutePosition();
  20946. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20947. if (!this._collider) {
  20948. this._collider = new BABYLON.Collider();
  20949. }
  20950. this._collider._radius = this.ellipsoid;
  20951. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20952. return this;
  20953. };
  20954. // Collisions
  20955. /** @hidden */
  20956. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20957. this._generatePointsArray();
  20958. if (!this._positions) {
  20959. return this;
  20960. }
  20961. // Transformation
  20962. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20963. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20964. subMesh._lastColliderWorldVertices = [];
  20965. subMesh._trianglePlanes = [];
  20966. var start = subMesh.verticesStart;
  20967. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20968. for (var i = start; i < end; i++) {
  20969. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20970. }
  20971. }
  20972. // Collide
  20973. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20974. if (collider.collisionFound) {
  20975. collider.collidedMesh = this;
  20976. }
  20977. return this;
  20978. };
  20979. /** @hidden */
  20980. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20981. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20982. var len = subMeshes.length;
  20983. for (var index = 0; index < len; index++) {
  20984. var subMesh = subMeshes.data[index];
  20985. // Bounding test
  20986. if (len > 1 && !subMesh._checkCollision(collider))
  20987. continue;
  20988. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20989. }
  20990. return this;
  20991. };
  20992. /** @hidden */
  20993. AbstractMesh.prototype._checkCollision = function (collider) {
  20994. // Bounding box test
  20995. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20996. return this;
  20997. // Transformation matrix
  20998. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20999. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21000. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21001. return this;
  21002. };
  21003. // Picking
  21004. /** @hidden */
  21005. AbstractMesh.prototype._generatePointsArray = function () {
  21006. return false;
  21007. };
  21008. /**
  21009. * Checks if the passed Ray intersects with the mesh
  21010. * @param ray defines the ray to use
  21011. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21012. * @returns the picking info
  21013. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21014. */
  21015. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21016. var pickingInfo = new BABYLON.PickingInfo();
  21017. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21018. return pickingInfo;
  21019. }
  21020. if (!this._generatePointsArray()) {
  21021. return pickingInfo;
  21022. }
  21023. var intersectInfo = null;
  21024. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21025. var len = subMeshes.length;
  21026. for (var index = 0; index < len; index++) {
  21027. var subMesh = subMeshes.data[index];
  21028. // Bounding test
  21029. if (len > 1 && !subMesh.canIntersects(ray))
  21030. continue;
  21031. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21032. if (currentIntersectInfo) {
  21033. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21034. intersectInfo = currentIntersectInfo;
  21035. intersectInfo.subMeshId = index;
  21036. if (fastCheck) {
  21037. break;
  21038. }
  21039. }
  21040. }
  21041. }
  21042. if (intersectInfo) {
  21043. // Get picked point
  21044. var world = this.getWorldMatrix();
  21045. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21046. var direction = ray.direction.clone();
  21047. direction = direction.scale(intersectInfo.distance);
  21048. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21049. var pickedPoint = worldOrigin.add(worldDirection);
  21050. // Return result
  21051. pickingInfo.hit = true;
  21052. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21053. pickingInfo.pickedPoint = pickedPoint;
  21054. pickingInfo.pickedMesh = this;
  21055. pickingInfo.bu = intersectInfo.bu || 0;
  21056. pickingInfo.bv = intersectInfo.bv || 0;
  21057. pickingInfo.faceId = intersectInfo.faceId;
  21058. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21059. return pickingInfo;
  21060. }
  21061. return pickingInfo;
  21062. };
  21063. /**
  21064. * Clones the current mesh
  21065. * @param name defines the mesh name
  21066. * @param newParent defines the new mesh parent
  21067. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21068. * @returns the new mesh
  21069. */
  21070. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21071. return null;
  21072. };
  21073. /**
  21074. * Disposes all the submeshes of the current meshnp
  21075. * @returns the current mesh
  21076. */
  21077. AbstractMesh.prototype.releaseSubMeshes = function () {
  21078. if (this.subMeshes) {
  21079. while (this.subMeshes.length) {
  21080. this.subMeshes[0].dispose();
  21081. }
  21082. }
  21083. else {
  21084. this.subMeshes = new Array();
  21085. }
  21086. return this;
  21087. };
  21088. /**
  21089. * Releases resources associated with this abstract mesh.
  21090. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21091. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21092. */
  21093. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21094. var _this = this;
  21095. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21096. var index;
  21097. // Smart Array Retainers.
  21098. this.getScene().freeActiveMeshes();
  21099. this.getScene().freeRenderingGroups();
  21100. // Action manager
  21101. if (this.actionManager !== undefined && this.actionManager !== null) {
  21102. this.actionManager.dispose();
  21103. this.actionManager = null;
  21104. }
  21105. // Skeleton
  21106. this._skeleton = null;
  21107. // Intersections in progress
  21108. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21109. var other = this._intersectionsInProgress[index];
  21110. var pos = other._intersectionsInProgress.indexOf(this);
  21111. other._intersectionsInProgress.splice(pos, 1);
  21112. }
  21113. this._intersectionsInProgress = [];
  21114. // Lights
  21115. var lights = this.getScene().lights;
  21116. lights.forEach(function (light) {
  21117. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21118. if (meshIndex !== -1) {
  21119. light.includedOnlyMeshes.splice(meshIndex, 1);
  21120. }
  21121. meshIndex = light.excludedMeshes.indexOf(_this);
  21122. if (meshIndex !== -1) {
  21123. light.excludedMeshes.splice(meshIndex, 1);
  21124. }
  21125. // Shadow generators
  21126. var generator = light.getShadowGenerator();
  21127. if (generator) {
  21128. var shadowMap = generator.getShadowMap();
  21129. if (shadowMap && shadowMap.renderList) {
  21130. meshIndex = shadowMap.renderList.indexOf(_this);
  21131. if (meshIndex !== -1) {
  21132. shadowMap.renderList.splice(meshIndex, 1);
  21133. }
  21134. }
  21135. }
  21136. });
  21137. // SubMeshes
  21138. if (this.getClassName() !== "InstancedMesh") {
  21139. this.releaseSubMeshes();
  21140. }
  21141. // Query
  21142. var engine = this.getScene().getEngine();
  21143. if (this._occlusionQuery) {
  21144. this._isOcclusionQueryInProgress = false;
  21145. engine.deleteQuery(this._occlusionQuery);
  21146. this._occlusionQuery = null;
  21147. }
  21148. // Engine
  21149. engine.wipeCaches();
  21150. // Remove from scene
  21151. this.getScene().removeMesh(this);
  21152. if (disposeMaterialAndTextures) {
  21153. if (this.material) {
  21154. this.material.dispose(false, true);
  21155. }
  21156. }
  21157. if (!doNotRecurse) {
  21158. // Particles
  21159. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21160. if (this.getScene().particleSystems[index].emitter === this) {
  21161. this.getScene().particleSystems[index].dispose();
  21162. index--;
  21163. }
  21164. }
  21165. }
  21166. // facet data
  21167. if (this._facetDataEnabled) {
  21168. this.disableFacetData();
  21169. }
  21170. this.onAfterWorldMatrixUpdateObservable.clear();
  21171. this.onCollideObservable.clear();
  21172. this.onCollisionPositionChangeObservable.clear();
  21173. this.onRebuildObservable.clear();
  21174. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21175. };
  21176. /**
  21177. * Adds the passed mesh as a child to the current mesh
  21178. * @param mesh defines the child mesh
  21179. * @returns the current mesh
  21180. */
  21181. AbstractMesh.prototype.addChild = function (mesh) {
  21182. mesh.setParent(this);
  21183. return this;
  21184. };
  21185. /**
  21186. * Removes the passed mesh from the current mesh children list
  21187. * @param mesh defines the child mesh
  21188. * @returns the current mesh
  21189. */
  21190. AbstractMesh.prototype.removeChild = function (mesh) {
  21191. mesh.setParent(null);
  21192. return this;
  21193. };
  21194. // Facet data
  21195. /** @hidden */
  21196. AbstractMesh.prototype._initFacetData = function () {
  21197. if (!this._facetNormals) {
  21198. this._facetNormals = new Array();
  21199. }
  21200. if (!this._facetPositions) {
  21201. this._facetPositions = new Array();
  21202. }
  21203. if (!this._facetPartitioning) {
  21204. this._facetPartitioning = new Array();
  21205. }
  21206. this._facetNb = (this.getIndices().length / 3) | 0;
  21207. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21208. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21209. for (var f = 0; f < this._facetNb; f++) {
  21210. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21211. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21212. }
  21213. this._facetDataEnabled = true;
  21214. return this;
  21215. };
  21216. /**
  21217. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21218. * This method can be called within the render loop.
  21219. * 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
  21220. * @returns the current mesh
  21221. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21222. */
  21223. AbstractMesh.prototype.updateFacetData = function () {
  21224. if (!this._facetDataEnabled) {
  21225. this._initFacetData();
  21226. }
  21227. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21228. var indices = this.getIndices();
  21229. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21230. var bInfo = this.getBoundingInfo();
  21231. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21232. // init arrays, matrix and sort function on first call
  21233. this._facetDepthSortEnabled = true;
  21234. if (indices instanceof Uint16Array) {
  21235. this._depthSortedIndices = new Uint16Array(indices);
  21236. }
  21237. else if (indices instanceof Uint32Array) {
  21238. this._depthSortedIndices = new Uint32Array(indices);
  21239. }
  21240. else {
  21241. var needs32bits = false;
  21242. for (var i = 0; i < indices.length; i++) {
  21243. if (indices[i] > 65535) {
  21244. needs32bits = true;
  21245. break;
  21246. }
  21247. }
  21248. if (needs32bits) {
  21249. this._depthSortedIndices = new Uint32Array(indices);
  21250. }
  21251. else {
  21252. this._depthSortedIndices = new Uint16Array(indices);
  21253. }
  21254. }
  21255. this._facetDepthSortFunction = function (f1, f2) {
  21256. return (f2.sqDistance - f1.sqDistance);
  21257. };
  21258. if (!this._facetDepthSortFrom) {
  21259. var camera = this.getScene().activeCamera;
  21260. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21261. }
  21262. this._depthSortedFacets = [];
  21263. for (var f = 0; f < this._facetNb; f++) {
  21264. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21265. this._depthSortedFacets.push(depthSortedFacet);
  21266. }
  21267. this._invertedMatrix = BABYLON.Matrix.Identity();
  21268. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21269. }
  21270. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21271. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21272. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21273. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21274. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21275. this._subDiv.max = this._partitioningSubdivisions;
  21276. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21277. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21278. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21279. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21280. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21281. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21282. // set the parameters for ComputeNormals()
  21283. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21284. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21285. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21286. this._facetParameters.bInfo = bInfo;
  21287. this._facetParameters.bbSize = this._bbSize;
  21288. this._facetParameters.subDiv = this._subDiv;
  21289. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21290. this._facetParameters.depthSort = this._facetDepthSort;
  21291. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21292. this.computeWorldMatrix(true);
  21293. this._worldMatrix.invertToRef(this._invertedMatrix);
  21294. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21295. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21296. }
  21297. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21298. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21299. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21300. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21301. var l = (this._depthSortedIndices.length / 3) | 0;
  21302. for (var f = 0; f < l; f++) {
  21303. var sind = this._depthSortedFacets[f].ind;
  21304. this._depthSortedIndices[f * 3] = indices[sind];
  21305. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21306. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21307. }
  21308. this.updateIndices(this._depthSortedIndices);
  21309. }
  21310. return this;
  21311. };
  21312. /**
  21313. * Returns the facetLocalNormals array.
  21314. * The normals are expressed in the mesh local spac
  21315. * @returns an array of Vector3
  21316. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21317. */
  21318. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21319. if (!this._facetNormals) {
  21320. this.updateFacetData();
  21321. }
  21322. return this._facetNormals;
  21323. };
  21324. /**
  21325. * Returns the facetLocalPositions array.
  21326. * The facet positions are expressed in the mesh local space
  21327. * @returns an array of Vector3
  21328. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21329. */
  21330. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21331. if (!this._facetPositions) {
  21332. this.updateFacetData();
  21333. }
  21334. return this._facetPositions;
  21335. };
  21336. /**
  21337. * Returns the facetLocalPartioning array
  21338. * @returns an array of array of numbers
  21339. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21340. */
  21341. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21342. if (!this._facetPartitioning) {
  21343. this.updateFacetData();
  21344. }
  21345. return this._facetPartitioning;
  21346. };
  21347. /**
  21348. * Returns the i-th facet position in the world system.
  21349. * This method allocates a new Vector3 per call
  21350. * @param i defines the facet index
  21351. * @returns a new Vector3
  21352. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21353. */
  21354. AbstractMesh.prototype.getFacetPosition = function (i) {
  21355. var pos = BABYLON.Vector3.Zero();
  21356. this.getFacetPositionToRef(i, pos);
  21357. return pos;
  21358. };
  21359. /**
  21360. * Sets the reference Vector3 with the i-th facet position in the world system
  21361. * @param i defines the facet index
  21362. * @param ref defines the target vector
  21363. * @returns the current mesh
  21364. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21365. */
  21366. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21367. var localPos = (this.getFacetLocalPositions())[i];
  21368. var world = this.getWorldMatrix();
  21369. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21370. return this;
  21371. };
  21372. /**
  21373. * Returns the i-th facet normal in the world system.
  21374. * This method allocates a new Vector3 per call
  21375. * @param i defines the facet index
  21376. * @returns a new Vector3
  21377. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21378. */
  21379. AbstractMesh.prototype.getFacetNormal = function (i) {
  21380. var norm = BABYLON.Vector3.Zero();
  21381. this.getFacetNormalToRef(i, norm);
  21382. return norm;
  21383. };
  21384. /**
  21385. * Sets the reference Vector3 with the i-th facet normal in the world system
  21386. * @param i defines the facet index
  21387. * @param ref defines the target vector
  21388. * @returns the current mesh
  21389. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21390. */
  21391. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21392. var localNorm = (this.getFacetLocalNormals())[i];
  21393. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21394. return this;
  21395. };
  21396. /**
  21397. * 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)
  21398. * @param x defines x coordinate
  21399. * @param y defines y coordinate
  21400. * @param z defines z coordinate
  21401. * @returns the array of facet indexes
  21402. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21403. */
  21404. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21405. var bInfo = this.getBoundingInfo();
  21406. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21407. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21408. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21409. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21410. return null;
  21411. }
  21412. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21413. };
  21414. /**
  21415. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21416. * @param projected sets as the (x,y,z) world projection on the facet
  21417. * @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
  21418. * @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
  21419. * @param x defines x coordinate
  21420. * @param y defines y coordinate
  21421. * @param z defines z coordinate
  21422. * @returns the face index if found (or null instead)
  21423. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21424. */
  21425. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21426. if (checkFace === void 0) { checkFace = false; }
  21427. if (facing === void 0) { facing = true; }
  21428. var world = this.getWorldMatrix();
  21429. var invMat = BABYLON.Tmp.Matrix[5];
  21430. world.invertToRef(invMat);
  21431. var invVect = BABYLON.Tmp.Vector3[8];
  21432. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21433. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21434. if (projected) {
  21435. // tranform the local computed projected vector to world coordinates
  21436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21437. }
  21438. return closest;
  21439. };
  21440. /**
  21441. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21442. * @param projected sets as the (x,y,z) local projection on the facet
  21443. * @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
  21444. * @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
  21445. * @param x defines x coordinate
  21446. * @param y defines y coordinate
  21447. * @param z defines z coordinate
  21448. * @returns the face index if found (or null instead)
  21449. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21450. */
  21451. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21452. if (checkFace === void 0) { checkFace = false; }
  21453. if (facing === void 0) { facing = true; }
  21454. var closest = null;
  21455. var tmpx = 0.0;
  21456. var tmpy = 0.0;
  21457. var tmpz = 0.0;
  21458. var d = 0.0; // tmp dot facet normal * facet position
  21459. var t0 = 0.0;
  21460. var projx = 0.0;
  21461. var projy = 0.0;
  21462. var projz = 0.0;
  21463. // Get all the facets in the same partitioning block than (x, y, z)
  21464. var facetPositions = this.getFacetLocalPositions();
  21465. var facetNormals = this.getFacetLocalNormals();
  21466. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21467. if (!facetsInBlock) {
  21468. return null;
  21469. }
  21470. // Get the closest facet to (x, y, z)
  21471. var shortest = Number.MAX_VALUE; // init distance vars
  21472. var tmpDistance = shortest;
  21473. var fib; // current facet in the block
  21474. var norm; // current facet normal
  21475. var p0; // current facet barycenter position
  21476. // loop on all the facets in the current partitioning block
  21477. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21478. fib = facetsInBlock[idx];
  21479. norm = facetNormals[fib];
  21480. p0 = facetPositions[fib];
  21481. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21482. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21483. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21484. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21485. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21486. projx = x + norm.x * t0;
  21487. projy = y + norm.y * t0;
  21488. projz = z + norm.z * t0;
  21489. tmpx = projx - x;
  21490. tmpy = projy - y;
  21491. tmpz = projz - z;
  21492. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21493. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21494. shortest = tmpDistance;
  21495. closest = fib;
  21496. if (projected) {
  21497. projected.x = projx;
  21498. projected.y = projy;
  21499. projected.z = projz;
  21500. }
  21501. }
  21502. }
  21503. }
  21504. return closest;
  21505. };
  21506. /**
  21507. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21508. * @returns the parameters
  21509. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21510. */
  21511. AbstractMesh.prototype.getFacetDataParameters = function () {
  21512. return this._facetParameters;
  21513. };
  21514. /**
  21515. * Disables the feature FacetData and frees the related memory
  21516. * @returns the current mesh
  21517. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21518. */
  21519. AbstractMesh.prototype.disableFacetData = function () {
  21520. if (this._facetDataEnabled) {
  21521. this._facetDataEnabled = false;
  21522. this._facetPositions = new Array();
  21523. this._facetNormals = new Array();
  21524. this._facetPartitioning = new Array();
  21525. this._facetParameters = null;
  21526. this._depthSortedIndices = new Uint32Array(0);
  21527. }
  21528. return this;
  21529. };
  21530. /**
  21531. * Updates the AbstractMesh indices array
  21532. * @param indices defines the data source
  21533. * @returns the current mesh
  21534. */
  21535. AbstractMesh.prototype.updateIndices = function (indices) {
  21536. return this;
  21537. };
  21538. /**
  21539. * Creates new normals data for the mesh
  21540. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21541. * @returns the current mesh
  21542. */
  21543. AbstractMesh.prototype.createNormals = function (updatable) {
  21544. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21545. var indices = this.getIndices();
  21546. var normals;
  21547. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21548. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21549. }
  21550. else {
  21551. normals = [];
  21552. }
  21553. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21554. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21555. return this;
  21556. };
  21557. /**
  21558. * Align the mesh with a normal
  21559. * @param normal defines the normal to use
  21560. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21561. * @returns the current mesh
  21562. */
  21563. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21564. if (!upDirection) {
  21565. upDirection = BABYLON.Axis.Y;
  21566. }
  21567. var axisX = BABYLON.Tmp.Vector3[0];
  21568. var axisZ = BABYLON.Tmp.Vector3[1];
  21569. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21570. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21571. if (this.rotationQuaternion) {
  21572. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21573. }
  21574. else {
  21575. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21576. }
  21577. return this;
  21578. };
  21579. /** @hidden */
  21580. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21581. this._isOccluded = false;
  21582. };
  21583. /** No occlusion */
  21584. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21585. /** Occlusion set to optimisitic */
  21586. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21587. /** Occlusion set to strict */
  21588. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21589. /** Use an accurante occlusion algorithm */
  21590. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21591. /** Use a conservative occlusion algorithm */
  21592. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21593. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21594. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21595. /** Culling strategy with bounding sphere only and then frustum culling */
  21596. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21597. return AbstractMesh;
  21598. }(BABYLON.TransformNode));
  21599. BABYLON.AbstractMesh = AbstractMesh;
  21600. })(BABYLON || (BABYLON = {}));
  21601. //# sourceMappingURL=babylon.abstractMesh.js.map
  21602. var BABYLON;
  21603. (function (BABYLON) {
  21604. /**
  21605. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21606. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21607. * 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.
  21608. */
  21609. var Light = /** @class */ (function (_super) {
  21610. __extends(Light, _super);
  21611. /**
  21612. * Creates a Light object in the scene.
  21613. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21614. * @param name The firendly name of the light
  21615. * @param scene The scene the light belongs too
  21616. */
  21617. function Light(name, scene) {
  21618. var _this = _super.call(this, name, scene) || this;
  21619. /**
  21620. * Diffuse gives the basic color to an object.
  21621. */
  21622. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21623. /**
  21624. * Specular produces a highlight color on an object.
  21625. * Note: This is note affecting PBR materials.
  21626. */
  21627. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21628. /**
  21629. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21630. * falling off base on range or angle.
  21631. * This can be set to any values in Light.FALLOFF_x.
  21632. *
  21633. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21634. * other types of materials.
  21635. */
  21636. _this.falloffType = Light.FALLOFF_DEFAULT;
  21637. /**
  21638. * Strength of the light.
  21639. * Note: By default it is define in the framework own unit.
  21640. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21641. */
  21642. _this.intensity = 1.0;
  21643. _this._range = Number.MAX_VALUE;
  21644. _this._inverseSquaredRange = 0;
  21645. /**
  21646. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21647. * of light.
  21648. */
  21649. _this._photometricScale = 1.0;
  21650. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21651. _this._radius = 0.00001;
  21652. /**
  21653. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21654. * exceeding the number allowed of the materials.
  21655. */
  21656. _this.renderPriority = 0;
  21657. _this._shadowEnabled = true;
  21658. _this._excludeWithLayerMask = 0;
  21659. _this._includeOnlyWithLayerMask = 0;
  21660. _this._lightmapMode = 0;
  21661. /**
  21662. * @hidden Internal use only.
  21663. */
  21664. _this._excludedMeshesIds = new Array();
  21665. /**
  21666. * @hidden Internal use only.
  21667. */
  21668. _this._includedOnlyMeshesIds = new Array();
  21669. _this.getScene().addLight(_this);
  21670. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21671. _this._buildUniformLayout();
  21672. _this.includedOnlyMeshes = new Array();
  21673. _this.excludedMeshes = new Array();
  21674. _this._resyncMeshes();
  21675. return _this;
  21676. }
  21677. Object.defineProperty(Light.prototype, "range", {
  21678. /**
  21679. * Defines how far from the source the light is impacting in scene units.
  21680. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21681. */
  21682. get: function () {
  21683. return this._range;
  21684. },
  21685. /**
  21686. * Defines how far from the source the light is impacting in scene units.
  21687. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21688. */
  21689. set: function (value) {
  21690. this._range = value;
  21691. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21692. },
  21693. enumerable: true,
  21694. configurable: true
  21695. });
  21696. Object.defineProperty(Light.prototype, "intensityMode", {
  21697. /**
  21698. * Gets the photometric scale used to interpret the intensity.
  21699. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21700. */
  21701. get: function () {
  21702. return this._intensityMode;
  21703. },
  21704. /**
  21705. * Sets the photometric scale used to interpret the intensity.
  21706. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21707. */
  21708. set: function (value) {
  21709. this._intensityMode = value;
  21710. this._computePhotometricScale();
  21711. },
  21712. enumerable: true,
  21713. configurable: true
  21714. });
  21715. ;
  21716. ;
  21717. Object.defineProperty(Light.prototype, "radius", {
  21718. /**
  21719. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21720. */
  21721. get: function () {
  21722. return this._radius;
  21723. },
  21724. /**
  21725. * sets the light radius used by PBR Materials to simulate soft area lights.
  21726. */
  21727. set: function (value) {
  21728. this._radius = value;
  21729. this._computePhotometricScale();
  21730. },
  21731. enumerable: true,
  21732. configurable: true
  21733. });
  21734. ;
  21735. ;
  21736. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21737. /**
  21738. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21739. * the current shadow generator.
  21740. */
  21741. get: function () {
  21742. return this._shadowEnabled;
  21743. },
  21744. /**
  21745. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21746. * the current shadow generator.
  21747. */
  21748. set: function (value) {
  21749. if (this._shadowEnabled === value) {
  21750. return;
  21751. }
  21752. this._shadowEnabled = value;
  21753. this._markMeshesAsLightDirty();
  21754. },
  21755. enumerable: true,
  21756. configurable: true
  21757. });
  21758. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21759. /**
  21760. * Gets the only meshes impacted by this light.
  21761. */
  21762. get: function () {
  21763. return this._includedOnlyMeshes;
  21764. },
  21765. /**
  21766. * Sets the only meshes impacted by this light.
  21767. */
  21768. set: function (value) {
  21769. this._includedOnlyMeshes = value;
  21770. this._hookArrayForIncludedOnly(value);
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21776. /**
  21777. * Gets the meshes not impacted by this light.
  21778. */
  21779. get: function () {
  21780. return this._excludedMeshes;
  21781. },
  21782. /**
  21783. * Sets the meshes not impacted by this light.
  21784. */
  21785. set: function (value) {
  21786. this._excludedMeshes = value;
  21787. this._hookArrayForExcluded(value);
  21788. },
  21789. enumerable: true,
  21790. configurable: true
  21791. });
  21792. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21793. /**
  21794. * Gets the layer id use to find what meshes are not impacted by the light.
  21795. * Inactive if 0
  21796. */
  21797. get: function () {
  21798. return this._excludeWithLayerMask;
  21799. },
  21800. /**
  21801. * Sets the layer id use to find what meshes are not impacted by the light.
  21802. * Inactive if 0
  21803. */
  21804. set: function (value) {
  21805. this._excludeWithLayerMask = value;
  21806. this._resyncMeshes();
  21807. },
  21808. enumerable: true,
  21809. configurable: true
  21810. });
  21811. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21812. /**
  21813. * Gets the layer id use to find what meshes are impacted by the light.
  21814. * Inactive if 0
  21815. */
  21816. get: function () {
  21817. return this._includeOnlyWithLayerMask;
  21818. },
  21819. /**
  21820. * Sets the layer id use to find what meshes are impacted by the light.
  21821. * Inactive if 0
  21822. */
  21823. set: function (value) {
  21824. this._includeOnlyWithLayerMask = value;
  21825. this._resyncMeshes();
  21826. },
  21827. enumerable: true,
  21828. configurable: true
  21829. });
  21830. Object.defineProperty(Light.prototype, "lightmapMode", {
  21831. /**
  21832. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21833. */
  21834. get: function () {
  21835. return this._lightmapMode;
  21836. },
  21837. /**
  21838. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21839. */
  21840. set: function (value) {
  21841. if (this._lightmapMode === value) {
  21842. return;
  21843. }
  21844. this._lightmapMode = value;
  21845. this._markMeshesAsLightDirty();
  21846. },
  21847. enumerable: true,
  21848. configurable: true
  21849. });
  21850. /**
  21851. * Returns the string "Light".
  21852. * @returns the class name
  21853. */
  21854. Light.prototype.getClassName = function () {
  21855. return "Light";
  21856. };
  21857. /**
  21858. * Converts the light information to a readable string for debug purpose.
  21859. * @param fullDetails Supports for multiple levels of logging within scene loading
  21860. * @returns the human readable light info
  21861. */
  21862. Light.prototype.toString = function (fullDetails) {
  21863. var ret = "Name: " + this.name;
  21864. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21865. if (this.animations) {
  21866. for (var i = 0; i < this.animations.length; i++) {
  21867. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21868. }
  21869. }
  21870. if (fullDetails) {
  21871. }
  21872. return ret;
  21873. };
  21874. /** @hidden */
  21875. Light.prototype._syncParentEnabledState = function () {
  21876. _super.prototype._syncParentEnabledState.call(this);
  21877. this._resyncMeshes();
  21878. };
  21879. /**
  21880. * Set the enabled state of this node.
  21881. * @param value - the new enabled state
  21882. */
  21883. Light.prototype.setEnabled = function (value) {
  21884. _super.prototype.setEnabled.call(this, value);
  21885. this._resyncMeshes();
  21886. };
  21887. /**
  21888. * Returns the Light associated shadow generator if any.
  21889. * @return the associated shadow generator.
  21890. */
  21891. Light.prototype.getShadowGenerator = function () {
  21892. return this._shadowGenerator;
  21893. };
  21894. /**
  21895. * Returns a Vector3, the absolute light position in the World.
  21896. * @returns the world space position of the light
  21897. */
  21898. Light.prototype.getAbsolutePosition = function () {
  21899. return BABYLON.Vector3.Zero();
  21900. };
  21901. /**
  21902. * Specifies if the light will affect the passed mesh.
  21903. * @param mesh The mesh to test against the light
  21904. * @return true the mesh is affected otherwise, false.
  21905. */
  21906. Light.prototype.canAffectMesh = function (mesh) {
  21907. if (!mesh) {
  21908. return true;
  21909. }
  21910. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21911. return false;
  21912. }
  21913. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21914. return false;
  21915. }
  21916. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21917. return false;
  21918. }
  21919. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21920. return false;
  21921. }
  21922. return true;
  21923. };
  21924. /**
  21925. * Sort function to order lights for rendering.
  21926. * @param a First Light object to compare to second.
  21927. * @param b Second Light object to compare first.
  21928. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21929. */
  21930. Light.CompareLightsPriority = function (a, b) {
  21931. //shadow-casting lights have priority over non-shadow-casting lights
  21932. //the renderPrioirty is a secondary sort criterion
  21933. if (a.shadowEnabled !== b.shadowEnabled) {
  21934. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21935. }
  21936. return b.renderPriority - a.renderPriority;
  21937. };
  21938. /**
  21939. * Releases resources associated with this node.
  21940. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21941. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21942. */
  21943. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21944. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21945. if (this._shadowGenerator) {
  21946. this._shadowGenerator.dispose();
  21947. this._shadowGenerator = null;
  21948. }
  21949. // Animations
  21950. this.getScene().stopAnimation(this);
  21951. // Remove from meshes
  21952. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21953. var mesh = _a[_i];
  21954. mesh._removeLightSource(this);
  21955. }
  21956. this._uniformBuffer.dispose();
  21957. // Remove from scene
  21958. this.getScene().removeLight(this);
  21959. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21960. };
  21961. /**
  21962. * Returns the light type ID (integer).
  21963. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21964. */
  21965. Light.prototype.getTypeID = function () {
  21966. return 0;
  21967. };
  21968. /**
  21969. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21970. * @returns the scaled intensity in intensity mode unit
  21971. */
  21972. Light.prototype.getScaledIntensity = function () {
  21973. return this._photometricScale * this.intensity;
  21974. };
  21975. /**
  21976. * Returns a new Light object, named "name", from the current one.
  21977. * @param name The name of the cloned light
  21978. * @returns the new created light
  21979. */
  21980. Light.prototype.clone = function (name) {
  21981. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21982. if (!constructor) {
  21983. return null;
  21984. }
  21985. return BABYLON.SerializationHelper.Clone(constructor, this);
  21986. };
  21987. /**
  21988. * Serializes the current light into a Serialization object.
  21989. * @returns the serialized object.
  21990. */
  21991. Light.prototype.serialize = function () {
  21992. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21993. // Type
  21994. serializationObject.type = this.getTypeID();
  21995. // Parent
  21996. if (this.parent) {
  21997. serializationObject.parentId = this.parent.id;
  21998. }
  21999. // Inclusion / exclusions
  22000. if (this.excludedMeshes.length > 0) {
  22001. serializationObject.excludedMeshesIds = [];
  22002. this.excludedMeshes.forEach(function (mesh) {
  22003. serializationObject.excludedMeshesIds.push(mesh.id);
  22004. });
  22005. }
  22006. if (this.includedOnlyMeshes.length > 0) {
  22007. serializationObject.includedOnlyMeshesIds = [];
  22008. this.includedOnlyMeshes.forEach(function (mesh) {
  22009. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22010. });
  22011. }
  22012. // Animations
  22013. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22014. serializationObject.ranges = this.serializeAnimationRanges();
  22015. return serializationObject;
  22016. };
  22017. /**
  22018. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22019. * This new light is named "name" and added to the passed scene.
  22020. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22021. * @param name The friendly name of the light
  22022. * @param scene The scene the new light will belong to
  22023. * @returns the constructor function
  22024. */
  22025. Light.GetConstructorFromName = function (type, name, scene) {
  22026. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22027. if (constructorFunc) {
  22028. return constructorFunc;
  22029. }
  22030. // Default to no light for none present once.
  22031. return null;
  22032. };
  22033. /**
  22034. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22035. * @param parsedLight The JSON representation of the light
  22036. * @param scene The scene to create the parsed light in
  22037. * @returns the created light after parsing
  22038. */
  22039. Light.Parse = function (parsedLight, scene) {
  22040. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22041. if (!constructor) {
  22042. return null;
  22043. }
  22044. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22045. // Inclusion / exclusions
  22046. if (parsedLight.excludedMeshesIds) {
  22047. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22048. }
  22049. if (parsedLight.includedOnlyMeshesIds) {
  22050. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22051. }
  22052. // Parent
  22053. if (parsedLight.parentId) {
  22054. light._waitingParentId = parsedLight.parentId;
  22055. }
  22056. // Animations
  22057. if (parsedLight.animations) {
  22058. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22059. var parsedAnimation = parsedLight.animations[animationIndex];
  22060. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22061. }
  22062. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22063. }
  22064. if (parsedLight.autoAnimate) {
  22065. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22066. }
  22067. return light;
  22068. };
  22069. Light.prototype._hookArrayForExcluded = function (array) {
  22070. var _this = this;
  22071. var oldPush = array.push;
  22072. array.push = function () {
  22073. var items = [];
  22074. for (var _i = 0; _i < arguments.length; _i++) {
  22075. items[_i] = arguments[_i];
  22076. }
  22077. var result = oldPush.apply(array, items);
  22078. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22079. var item = items_1[_a];
  22080. item._resyncLighSource(_this);
  22081. }
  22082. return result;
  22083. };
  22084. var oldSplice = array.splice;
  22085. array.splice = function (index, deleteCount) {
  22086. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22087. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22088. var item = deleted_1[_i];
  22089. item._resyncLighSource(_this);
  22090. }
  22091. return deleted;
  22092. };
  22093. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22094. var item = array_1[_i];
  22095. item._resyncLighSource(this);
  22096. }
  22097. };
  22098. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22099. var _this = this;
  22100. var oldPush = array.push;
  22101. array.push = function () {
  22102. var items = [];
  22103. for (var _i = 0; _i < arguments.length; _i++) {
  22104. items[_i] = arguments[_i];
  22105. }
  22106. var result = oldPush.apply(array, items);
  22107. _this._resyncMeshes();
  22108. return result;
  22109. };
  22110. var oldSplice = array.splice;
  22111. array.splice = function (index, deleteCount) {
  22112. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22113. _this._resyncMeshes();
  22114. return deleted;
  22115. };
  22116. this._resyncMeshes();
  22117. };
  22118. Light.prototype._resyncMeshes = function () {
  22119. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22120. var mesh = _a[_i];
  22121. mesh._resyncLighSource(this);
  22122. }
  22123. };
  22124. /**
  22125. * Forces the meshes to update their light related information in their rendering used effects
  22126. * @hidden Internal Use Only
  22127. */
  22128. Light.prototype._markMeshesAsLightDirty = function () {
  22129. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22130. var mesh = _a[_i];
  22131. if (mesh._lightSources.indexOf(this) !== -1) {
  22132. mesh._markSubMeshesAsLightDirty();
  22133. }
  22134. }
  22135. };
  22136. /**
  22137. * Recomputes the cached photometric scale if needed.
  22138. */
  22139. Light.prototype._computePhotometricScale = function () {
  22140. this._photometricScale = this._getPhotometricScale();
  22141. this.getScene().resetCachedMaterial();
  22142. };
  22143. /**
  22144. * Returns the Photometric Scale according to the light type and intensity mode.
  22145. */
  22146. Light.prototype._getPhotometricScale = function () {
  22147. var photometricScale = 0.0;
  22148. var lightTypeID = this.getTypeID();
  22149. //get photometric mode
  22150. var photometricMode = this.intensityMode;
  22151. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22152. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22153. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22154. }
  22155. else {
  22156. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22157. }
  22158. }
  22159. //compute photometric scale
  22160. switch (lightTypeID) {
  22161. case Light.LIGHTTYPEID_POINTLIGHT:
  22162. case Light.LIGHTTYPEID_SPOTLIGHT:
  22163. switch (photometricMode) {
  22164. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22165. photometricScale = 1.0 / (4.0 * Math.PI);
  22166. break;
  22167. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22168. photometricScale = 1.0;
  22169. break;
  22170. case Light.INTENSITYMODE_LUMINANCE:
  22171. photometricScale = this.radius * this.radius;
  22172. break;
  22173. }
  22174. break;
  22175. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22176. switch (photometricMode) {
  22177. case Light.INTENSITYMODE_ILLUMINANCE:
  22178. photometricScale = 1.0;
  22179. break;
  22180. case Light.INTENSITYMODE_LUMINANCE:
  22181. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22182. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22183. var apexAngleRadians = this.radius;
  22184. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22185. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22186. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22187. photometricScale = solidAngle;
  22188. break;
  22189. }
  22190. break;
  22191. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22192. // No fall off in hemisperic light.
  22193. photometricScale = 1.0;
  22194. break;
  22195. }
  22196. return photometricScale;
  22197. };
  22198. /**
  22199. * Reorder the light in the scene according to their defined priority.
  22200. * @hidden Internal Use Only
  22201. */
  22202. Light.prototype._reorderLightsInScene = function () {
  22203. var scene = this.getScene();
  22204. if (this._renderPriority != 0) {
  22205. scene.requireLightSorting = true;
  22206. }
  22207. this.getScene().sortLightsByPriority();
  22208. };
  22209. /**
  22210. * Falloff Default: light is falling off following the material specification:
  22211. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22212. */
  22213. Light.FALLOFF_DEFAULT = 0;
  22214. /**
  22215. * Falloff Physical: light is falling off following the inverse squared distance law.
  22216. */
  22217. Light.FALLOFF_PHYSICAL = 1;
  22218. /**
  22219. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22220. * to enhance interoperability with other engines.
  22221. */
  22222. Light.FALLOFF_GLTF = 2;
  22223. /**
  22224. * Falloff Standard: light is falling off like in the standard material
  22225. * to enhance interoperability with other materials.
  22226. */
  22227. Light.FALLOFF_STANDARD = 3;
  22228. //lightmapMode Consts
  22229. /**
  22230. * If every light affecting the material is in this lightmapMode,
  22231. * material.lightmapTexture adds or multiplies
  22232. * (depends on material.useLightmapAsShadowmap)
  22233. * after every other light calculations.
  22234. */
  22235. Light.LIGHTMAP_DEFAULT = 0;
  22236. /**
  22237. * material.lightmapTexture as only diffuse lighting from this light
  22238. * adds only specular lighting from this light
  22239. * adds dynamic shadows
  22240. */
  22241. Light.LIGHTMAP_SPECULAR = 1;
  22242. /**
  22243. * material.lightmapTexture as only lighting
  22244. * no light calculation from this light
  22245. * only adds dynamic shadows from this light
  22246. */
  22247. Light.LIGHTMAP_SHADOWSONLY = 2;
  22248. // Intensity Mode Consts
  22249. /**
  22250. * Each light type uses the default quantity according to its type:
  22251. * point/spot lights use luminous intensity
  22252. * directional lights use illuminance
  22253. */
  22254. Light.INTENSITYMODE_AUTOMATIC = 0;
  22255. /**
  22256. * lumen (lm)
  22257. */
  22258. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22259. /**
  22260. * candela (lm/sr)
  22261. */
  22262. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22263. /**
  22264. * lux (lm/m^2)
  22265. */
  22266. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22267. /**
  22268. * nit (cd/m^2)
  22269. */
  22270. Light.INTENSITYMODE_LUMINANCE = 4;
  22271. // Light types ids const.
  22272. /**
  22273. * Light type const id of the point light.
  22274. */
  22275. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22276. /**
  22277. * Light type const id of the directional light.
  22278. */
  22279. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22280. /**
  22281. * Light type const id of the spot light.
  22282. */
  22283. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22284. /**
  22285. * Light type const id of the hemispheric light.
  22286. */
  22287. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22288. __decorate([
  22289. BABYLON.serializeAsColor3()
  22290. ], Light.prototype, "diffuse", void 0);
  22291. __decorate([
  22292. BABYLON.serializeAsColor3()
  22293. ], Light.prototype, "specular", void 0);
  22294. __decorate([
  22295. BABYLON.serialize()
  22296. ], Light.prototype, "falloffType", void 0);
  22297. __decorate([
  22298. BABYLON.serialize()
  22299. ], Light.prototype, "intensity", void 0);
  22300. __decorate([
  22301. BABYLON.serialize()
  22302. ], Light.prototype, "range", null);
  22303. __decorate([
  22304. BABYLON.serialize()
  22305. ], Light.prototype, "intensityMode", null);
  22306. __decorate([
  22307. BABYLON.serialize()
  22308. ], Light.prototype, "radius", null);
  22309. __decorate([
  22310. BABYLON.serialize()
  22311. ], Light.prototype, "_renderPriority", void 0);
  22312. __decorate([
  22313. BABYLON.expandToProperty("_reorderLightsInScene")
  22314. ], Light.prototype, "renderPriority", void 0);
  22315. __decorate([
  22316. BABYLON.serialize("shadowEnabled")
  22317. ], Light.prototype, "_shadowEnabled", void 0);
  22318. __decorate([
  22319. BABYLON.serialize("excludeWithLayerMask")
  22320. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22321. __decorate([
  22322. BABYLON.serialize("includeOnlyWithLayerMask")
  22323. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22324. __decorate([
  22325. BABYLON.serialize("lightmapMode")
  22326. ], Light.prototype, "_lightmapMode", void 0);
  22327. return Light;
  22328. }(BABYLON.Node));
  22329. BABYLON.Light = Light;
  22330. })(BABYLON || (BABYLON = {}));
  22331. //# sourceMappingURL=babylon.light.js.map
  22332. var BABYLON;
  22333. (function (BABYLON) {
  22334. /**
  22335. * This is the base class of all the camera used in the application.
  22336. * @see http://doc.babylonjs.com/features/cameras
  22337. */
  22338. var Camera = /** @class */ (function (_super) {
  22339. __extends(Camera, _super);
  22340. /**
  22341. * Instantiates a new camera object.
  22342. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22343. * @see http://doc.babylonjs.com/features/cameras
  22344. * @param name Defines the name of the camera in the scene
  22345. * @param position Defines the position of the camera
  22346. * @param scene Defines the scene the camera belongs too
  22347. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22348. */
  22349. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22350. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22351. var _this = _super.call(this, name, scene) || this;
  22352. /**
  22353. * The vector the camera should consider as up.
  22354. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22355. */
  22356. _this.upVector = BABYLON.Vector3.Up();
  22357. /**
  22358. * Define the current limit on the left side for an orthographic camera
  22359. * In scene unit
  22360. */
  22361. _this.orthoLeft = null;
  22362. /**
  22363. * Define the current limit on the right side for an orthographic camera
  22364. * In scene unit
  22365. */
  22366. _this.orthoRight = null;
  22367. /**
  22368. * Define the current limit on the bottom side for an orthographic camera
  22369. * In scene unit
  22370. */
  22371. _this.orthoBottom = null;
  22372. /**
  22373. * Define the current limit on the top side for an orthographic camera
  22374. * In scene unit
  22375. */
  22376. _this.orthoTop = null;
  22377. /**
  22378. * Field Of View is set in Radians. (default is 0.8)
  22379. */
  22380. _this.fov = 0.8;
  22381. /**
  22382. * Define the minimum distance the camera can see from.
  22383. * This is important to note that the depth buffer are not infinite and the closer it starts
  22384. * the more your scene might encounter depth fighting issue.
  22385. */
  22386. _this.minZ = 1;
  22387. /**
  22388. * Define the maximum distance the camera can see to.
  22389. * This is important to note that the depth buffer are not infinite and the further it end
  22390. * the more your scene might encounter depth fighting issue.
  22391. */
  22392. _this.maxZ = 10000.0;
  22393. /**
  22394. * Define the default inertia of the camera.
  22395. * This helps giving a smooth feeling to the camera movement.
  22396. */
  22397. _this.inertia = 0.9;
  22398. /**
  22399. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22400. */
  22401. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22402. /**
  22403. * Define wether the camera is intermediate.
  22404. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22405. */
  22406. _this.isIntermediate = false;
  22407. /**
  22408. * Define the viewport of the camera.
  22409. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22410. */
  22411. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22412. /**
  22413. * Restricts the camera to viewing objects with the same layerMask.
  22414. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22415. */
  22416. _this.layerMask = 0x0FFFFFFF;
  22417. /**
  22418. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22419. */
  22420. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22421. /**
  22422. * Rig mode of the camera.
  22423. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22424. * This is normally controlled byt the camera themselves as internal use.
  22425. */
  22426. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22427. /**
  22428. * Defines the list of custom render target the camera should render to.
  22429. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22430. * else in the scene.
  22431. */
  22432. _this.customRenderTargets = new Array();
  22433. /**
  22434. * Observable triggered when the camera view matrix has changed.
  22435. */
  22436. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22437. /**
  22438. * Observable triggered when the camera Projection matrix has changed.
  22439. */
  22440. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22441. /**
  22442. * Observable triggered when the inputs have been processed.
  22443. */
  22444. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22445. /**
  22446. * Observable triggered when reset has been called and applied to the camera.
  22447. */
  22448. _this.onRestoreStateObservable = new BABYLON.Observable();
  22449. /** @hidden */
  22450. _this._rigCameras = new Array();
  22451. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22452. /** @hidden */
  22453. _this._skipRendering = false;
  22454. /** @hidden */
  22455. _this._projectionMatrix = new BABYLON.Matrix();
  22456. /** @hidden */
  22457. _this._postProcesses = new Array();
  22458. /** @hidden */
  22459. _this._activeMeshes = new BABYLON.SmartArray(256);
  22460. _this._globalPosition = BABYLON.Vector3.Zero();
  22461. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22462. _this._doNotComputeProjectionMatrix = false;
  22463. _this._transformMatrix = BABYLON.Matrix.Zero();
  22464. _this._refreshFrustumPlanes = true;
  22465. _this.getScene().addCamera(_this);
  22466. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22467. _this.getScene().activeCamera = _this;
  22468. }
  22469. _this.position = position;
  22470. return _this;
  22471. }
  22472. /**
  22473. * Store current camera state (fov, position, etc..)
  22474. * @returns the camera
  22475. */
  22476. Camera.prototype.storeState = function () {
  22477. this._stateStored = true;
  22478. this._storedFov = this.fov;
  22479. return this;
  22480. };
  22481. /**
  22482. * Restores the camera state values if it has been stored. You must call storeState() first
  22483. */
  22484. Camera.prototype._restoreStateValues = function () {
  22485. if (!this._stateStored) {
  22486. return false;
  22487. }
  22488. this.fov = this._storedFov;
  22489. return true;
  22490. };
  22491. /**
  22492. * Restored camera state. You must call storeState() first.
  22493. * @returns true if restored and false otherwise
  22494. */
  22495. Camera.prototype.restoreState = function () {
  22496. if (this._restoreStateValues()) {
  22497. this.onRestoreStateObservable.notifyObservers(this);
  22498. return true;
  22499. }
  22500. return false;
  22501. };
  22502. /**
  22503. * Gets the class name of the camera.
  22504. * @returns the class name
  22505. */
  22506. Camera.prototype.getClassName = function () {
  22507. return "Camera";
  22508. };
  22509. /**
  22510. * Gets a string representation of the camera usefull for debug purpose.
  22511. * @param fullDetails Defines that a more verboe level of logging is required
  22512. * @returns the string representation
  22513. */
  22514. Camera.prototype.toString = function (fullDetails) {
  22515. var ret = "Name: " + this.name;
  22516. ret += ", type: " + this.getClassName();
  22517. if (this.animations) {
  22518. for (var i = 0; i < this.animations.length; i++) {
  22519. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22520. }
  22521. }
  22522. if (fullDetails) {
  22523. }
  22524. return ret;
  22525. };
  22526. Object.defineProperty(Camera.prototype, "globalPosition", {
  22527. /**
  22528. * Gets the current world space position of the camera.
  22529. */
  22530. get: function () {
  22531. return this._globalPosition;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. /**
  22537. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22538. * @returns the active meshe list
  22539. */
  22540. Camera.prototype.getActiveMeshes = function () {
  22541. return this._activeMeshes;
  22542. };
  22543. /**
  22544. * Check wether a mesh is part of the current active mesh list of the camera
  22545. * @param mesh Defines the mesh to check
  22546. * @returns true if active, false otherwise
  22547. */
  22548. Camera.prototype.isActiveMesh = function (mesh) {
  22549. return (this._activeMeshes.indexOf(mesh) !== -1);
  22550. };
  22551. /**
  22552. * Is this camera ready to be used/rendered
  22553. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22554. * @return true if the camera is ready
  22555. */
  22556. Camera.prototype.isReady = function (completeCheck) {
  22557. if (completeCheck === void 0) { completeCheck = false; }
  22558. if (completeCheck) {
  22559. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22560. var pp = _a[_i];
  22561. if (pp && !pp.isReady()) {
  22562. return false;
  22563. }
  22564. }
  22565. }
  22566. return _super.prototype.isReady.call(this, completeCheck);
  22567. };
  22568. /** @hidden */
  22569. Camera.prototype._initCache = function () {
  22570. _super.prototype._initCache.call(this);
  22571. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22572. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22573. this._cache.mode = undefined;
  22574. this._cache.minZ = undefined;
  22575. this._cache.maxZ = undefined;
  22576. this._cache.fov = undefined;
  22577. this._cache.fovMode = undefined;
  22578. this._cache.aspectRatio = undefined;
  22579. this._cache.orthoLeft = undefined;
  22580. this._cache.orthoRight = undefined;
  22581. this._cache.orthoBottom = undefined;
  22582. this._cache.orthoTop = undefined;
  22583. this._cache.renderWidth = undefined;
  22584. this._cache.renderHeight = undefined;
  22585. };
  22586. /** @hidden */
  22587. Camera.prototype._updateCache = function (ignoreParentClass) {
  22588. if (!ignoreParentClass) {
  22589. _super.prototype._updateCache.call(this);
  22590. }
  22591. this._cache.position.copyFrom(this.position);
  22592. this._cache.upVector.copyFrom(this.upVector);
  22593. };
  22594. /** @hidden */
  22595. Camera.prototype._isSynchronized = function () {
  22596. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22597. };
  22598. /** @hidden */
  22599. Camera.prototype._isSynchronizedViewMatrix = function () {
  22600. if (!_super.prototype._isSynchronized.call(this))
  22601. return false;
  22602. return this._cache.position.equals(this.position)
  22603. && this._cache.upVector.equals(this.upVector)
  22604. && this.isSynchronizedWithParent();
  22605. };
  22606. /** @hidden */
  22607. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22608. var check = this._cache.mode === this.mode
  22609. && this._cache.minZ === this.minZ
  22610. && this._cache.maxZ === this.maxZ;
  22611. if (!check) {
  22612. return false;
  22613. }
  22614. var engine = this.getEngine();
  22615. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22616. check = this._cache.fov === this.fov
  22617. && this._cache.fovMode === this.fovMode
  22618. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22619. }
  22620. else {
  22621. check = this._cache.orthoLeft === this.orthoLeft
  22622. && this._cache.orthoRight === this.orthoRight
  22623. && this._cache.orthoBottom === this.orthoBottom
  22624. && this._cache.orthoTop === this.orthoTop
  22625. && this._cache.renderWidth === engine.getRenderWidth()
  22626. && this._cache.renderHeight === engine.getRenderHeight();
  22627. }
  22628. return check;
  22629. };
  22630. /**
  22631. * Attach the input controls to a specific dom element to get the input from.
  22632. * @param element Defines the element the controls should be listened from
  22633. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22634. */
  22635. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22636. };
  22637. /**
  22638. * Detach the current controls from the specified dom element.
  22639. * @param element Defines the element to stop listening the inputs from
  22640. */
  22641. Camera.prototype.detachControl = function (element) {
  22642. };
  22643. /**
  22644. * Update the camera state according to the different inputs gathered during the frame.
  22645. */
  22646. Camera.prototype.update = function () {
  22647. this._checkInputs();
  22648. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22649. this._updateRigCameras();
  22650. }
  22651. };
  22652. /** @hidden */
  22653. Camera.prototype._checkInputs = function () {
  22654. this.onAfterCheckInputsObservable.notifyObservers(this);
  22655. };
  22656. Object.defineProperty(Camera.prototype, "rigCameras", {
  22657. /** @hidden */
  22658. get: function () {
  22659. return this._rigCameras;
  22660. },
  22661. enumerable: true,
  22662. configurable: true
  22663. });
  22664. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22665. get: function () {
  22666. return this._rigPostProcess;
  22667. },
  22668. enumerable: true,
  22669. configurable: true
  22670. });
  22671. /**
  22672. * Internal, gets the first post proces.
  22673. * @returns the first post process to be run on this camera.
  22674. */
  22675. Camera.prototype._getFirstPostProcess = function () {
  22676. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22677. if (this._postProcesses[ppIndex] !== null) {
  22678. return this._postProcesses[ppIndex];
  22679. }
  22680. }
  22681. return null;
  22682. };
  22683. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22684. // invalidate framebuffer
  22685. var firstPostProcess = this._getFirstPostProcess();
  22686. if (firstPostProcess) {
  22687. firstPostProcess.markTextureDirty();
  22688. }
  22689. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22690. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22691. var cam = this._rigCameras[i];
  22692. var rigPostProcess = cam._rigPostProcess;
  22693. // for VR rig, there does not have to be a post process
  22694. if (rigPostProcess) {
  22695. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22696. if (isPass) {
  22697. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22698. cam.isIntermediate = this._postProcesses.length === 0;
  22699. }
  22700. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22701. rigPostProcess.markTextureDirty();
  22702. }
  22703. else {
  22704. cam._postProcesses = this._postProcesses.slice(0);
  22705. }
  22706. }
  22707. };
  22708. /**
  22709. * Attach a post process to the camera.
  22710. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22711. * @param postProcess The post process to attach to the camera
  22712. * @param insertAt The position of the post process in case several of them are in use in the scene
  22713. * @returns the position the post process has been inserted at
  22714. */
  22715. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22716. if (insertAt === void 0) { insertAt = null; }
  22717. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22718. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22719. return 0;
  22720. }
  22721. if (insertAt == null || insertAt < 0) {
  22722. this._postProcesses.push(postProcess);
  22723. }
  22724. else if (this._postProcesses[insertAt] === null) {
  22725. this._postProcesses[insertAt] = postProcess;
  22726. }
  22727. else {
  22728. this._postProcesses.splice(insertAt, 0, postProcess);
  22729. }
  22730. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22731. return this._postProcesses.indexOf(postProcess);
  22732. };
  22733. /**
  22734. * Detach a post process to the camera.
  22735. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22736. * @param postProcess The post process to detach from the camera
  22737. */
  22738. Camera.prototype.detachPostProcess = function (postProcess) {
  22739. var idx = this._postProcesses.indexOf(postProcess);
  22740. if (idx !== -1) {
  22741. this._postProcesses[idx] = null;
  22742. }
  22743. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22744. };
  22745. /**
  22746. * Gets the current world matrix of the camera
  22747. */
  22748. Camera.prototype.getWorldMatrix = function () {
  22749. if (this._isSynchronizedViewMatrix()) {
  22750. return this._worldMatrix;
  22751. }
  22752. // Getting the the view matrix will also compute the world matrix.
  22753. this.getViewMatrix();
  22754. return this._worldMatrix;
  22755. };
  22756. /** @hidden */
  22757. Camera.prototype._getViewMatrix = function () {
  22758. return BABYLON.Matrix.Identity();
  22759. };
  22760. /**
  22761. * Gets the current view matrix of the camera.
  22762. * @param force forces the camera to recompute the matrix without looking at the cached state
  22763. * @returns the view matrix
  22764. */
  22765. Camera.prototype.getViewMatrix = function (force) {
  22766. if (!force && this._isSynchronizedViewMatrix()) {
  22767. return this._computedViewMatrix;
  22768. }
  22769. this.updateCache();
  22770. this._computedViewMatrix = this._getViewMatrix();
  22771. this._currentRenderId = this.getScene().getRenderId();
  22772. this._childRenderId = this._currentRenderId;
  22773. this._refreshFrustumPlanes = true;
  22774. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22775. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22776. }
  22777. this.onViewMatrixChangedObservable.notifyObservers(this);
  22778. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22779. return this._computedViewMatrix;
  22780. };
  22781. /**
  22782. * Freeze the projection matrix.
  22783. * It will prevent the cache check of the camera projection compute and can speed up perf
  22784. * if no parameter of the camera are meant to change
  22785. * @param projection Defines manually a projection if necessary
  22786. */
  22787. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22788. this._doNotComputeProjectionMatrix = true;
  22789. if (projection !== undefined) {
  22790. this._projectionMatrix = projection;
  22791. }
  22792. };
  22793. ;
  22794. /**
  22795. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22796. */
  22797. Camera.prototype.unfreezeProjectionMatrix = function () {
  22798. this._doNotComputeProjectionMatrix = false;
  22799. };
  22800. ;
  22801. /**
  22802. * Gets the current projection matrix of the camera.
  22803. * @param force forces the camera to recompute the matrix without looking at the cached state
  22804. * @returns the projection matrix
  22805. */
  22806. Camera.prototype.getProjectionMatrix = function (force) {
  22807. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22808. return this._projectionMatrix;
  22809. }
  22810. // Cache
  22811. this._cache.mode = this.mode;
  22812. this._cache.minZ = this.minZ;
  22813. this._cache.maxZ = this.maxZ;
  22814. // Matrix
  22815. this._refreshFrustumPlanes = true;
  22816. var engine = this.getEngine();
  22817. var scene = this.getScene();
  22818. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22819. this._cache.fov = this.fov;
  22820. this._cache.fovMode = this.fovMode;
  22821. this._cache.aspectRatio = engine.getAspectRatio(this);
  22822. if (this.minZ <= 0) {
  22823. this.minZ = 0.1;
  22824. }
  22825. if (scene.useRightHandedSystem) {
  22826. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22827. }
  22828. else {
  22829. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22830. }
  22831. }
  22832. else {
  22833. var halfWidth = engine.getRenderWidth() / 2.0;
  22834. var halfHeight = engine.getRenderHeight() / 2.0;
  22835. if (scene.useRightHandedSystem) {
  22836. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22837. }
  22838. else {
  22839. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22840. }
  22841. this._cache.orthoLeft = this.orthoLeft;
  22842. this._cache.orthoRight = this.orthoRight;
  22843. this._cache.orthoBottom = this.orthoBottom;
  22844. this._cache.orthoTop = this.orthoTop;
  22845. this._cache.renderWidth = engine.getRenderWidth();
  22846. this._cache.renderHeight = engine.getRenderHeight();
  22847. }
  22848. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22849. return this._projectionMatrix;
  22850. };
  22851. /**
  22852. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22853. * @returns a Matrix
  22854. */
  22855. Camera.prototype.getTransformationMatrix = function () {
  22856. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22857. return this._transformMatrix;
  22858. };
  22859. Camera.prototype._updateFrustumPlanes = function () {
  22860. if (!this._refreshFrustumPlanes) {
  22861. return;
  22862. }
  22863. this.getTransformationMatrix();
  22864. if (!this._frustumPlanes) {
  22865. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22866. }
  22867. else {
  22868. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22869. }
  22870. this._refreshFrustumPlanes = false;
  22871. };
  22872. /**
  22873. * Checks if a cullable object (mesh...) is in the camera frustum
  22874. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22875. * @param target The object to check
  22876. * @returns true if the object is in frustum otherwise false
  22877. */
  22878. Camera.prototype.isInFrustum = function (target) {
  22879. this._updateFrustumPlanes();
  22880. return target.isInFrustum(this._frustumPlanes);
  22881. };
  22882. /**
  22883. * Checks if a cullable object (mesh...) is in the camera frustum
  22884. * Unlike isInFrustum this cheks the full bounding box
  22885. * @param target The object to check
  22886. * @returns true if the object is in frustum otherwise false
  22887. */
  22888. Camera.prototype.isCompletelyInFrustum = function (target) {
  22889. this._updateFrustumPlanes();
  22890. return target.isCompletelyInFrustum(this._frustumPlanes);
  22891. };
  22892. /**
  22893. * Gets a ray in the forward direction from the camera.
  22894. * @param length Defines the length of the ray to create
  22895. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22896. * @param origin Defines the start point of the ray which defaults to the camera position
  22897. * @returns the forward ray
  22898. */
  22899. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22900. if (length === void 0) { length = 100; }
  22901. if (!transform) {
  22902. transform = this.getWorldMatrix();
  22903. }
  22904. if (!origin) {
  22905. origin = this.position;
  22906. }
  22907. var forward = new BABYLON.Vector3(0, 0, 1);
  22908. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22909. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22910. return new BABYLON.Ray(origin, direction, length);
  22911. };
  22912. /**
  22913. * Releases resources associated with this node.
  22914. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22915. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22916. */
  22917. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22918. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22919. // Observables
  22920. this.onViewMatrixChangedObservable.clear();
  22921. this.onProjectionMatrixChangedObservable.clear();
  22922. this.onAfterCheckInputsObservable.clear();
  22923. this.onRestoreStateObservable.clear();
  22924. // Inputs
  22925. if (this.inputs) {
  22926. this.inputs.clear();
  22927. }
  22928. // Animations
  22929. this.getScene().stopAnimation(this);
  22930. // Remove from scene
  22931. this.getScene().removeCamera(this);
  22932. while (this._rigCameras.length > 0) {
  22933. var camera = this._rigCameras.pop();
  22934. if (camera) {
  22935. camera.dispose();
  22936. }
  22937. }
  22938. // Postprocesses
  22939. if (this._rigPostProcess) {
  22940. this._rigPostProcess.dispose(this);
  22941. this._rigPostProcess = null;
  22942. this._postProcesses = [];
  22943. }
  22944. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22945. this._rigPostProcess = null;
  22946. this._postProcesses = [];
  22947. }
  22948. else {
  22949. var i = this._postProcesses.length;
  22950. while (--i >= 0) {
  22951. var postProcess = this._postProcesses[i];
  22952. if (postProcess) {
  22953. postProcess.dispose(this);
  22954. }
  22955. }
  22956. }
  22957. // Render targets
  22958. var i = this.customRenderTargets.length;
  22959. while (--i >= 0) {
  22960. this.customRenderTargets[i].dispose();
  22961. }
  22962. this.customRenderTargets = [];
  22963. // Active Meshes
  22964. this._activeMeshes.dispose();
  22965. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22966. };
  22967. Object.defineProperty(Camera.prototype, "leftCamera", {
  22968. /**
  22969. * Gets the left camera of a rig setup in case of Rigged Camera
  22970. */
  22971. get: function () {
  22972. if (this._rigCameras.length < 1) {
  22973. return null;
  22974. }
  22975. return this._rigCameras[0];
  22976. },
  22977. enumerable: true,
  22978. configurable: true
  22979. });
  22980. Object.defineProperty(Camera.prototype, "rightCamera", {
  22981. /**
  22982. * Gets the right camera of a rig setup in case of Rigged Camera
  22983. */
  22984. get: function () {
  22985. if (this._rigCameras.length < 2) {
  22986. return null;
  22987. }
  22988. return this._rigCameras[1];
  22989. },
  22990. enumerable: true,
  22991. configurable: true
  22992. });
  22993. /**
  22994. * Gets the left camera target of a rig setup in case of Rigged Camera
  22995. * @returns the target position
  22996. */
  22997. Camera.prototype.getLeftTarget = function () {
  22998. if (this._rigCameras.length < 1) {
  22999. return null;
  23000. }
  23001. return this._rigCameras[0].getTarget();
  23002. };
  23003. /**
  23004. * Gets the right camera target of a rig setup in case of Rigged Camera
  23005. * @returns the target position
  23006. */
  23007. Camera.prototype.getRightTarget = function () {
  23008. if (this._rigCameras.length < 2) {
  23009. return null;
  23010. }
  23011. return this._rigCameras[1].getTarget();
  23012. };
  23013. /**
  23014. * @hidden
  23015. */
  23016. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23017. if (this.cameraRigMode === mode) {
  23018. return;
  23019. }
  23020. while (this._rigCameras.length > 0) {
  23021. var camera = this._rigCameras.pop();
  23022. if (camera) {
  23023. camera.dispose();
  23024. }
  23025. }
  23026. this.cameraRigMode = mode;
  23027. this._cameraRigParams = {};
  23028. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23029. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23030. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23031. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23032. // create the rig cameras, unless none
  23033. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23034. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23035. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23036. if (leftCamera && rightCamera) {
  23037. this._rigCameras.push(leftCamera);
  23038. this._rigCameras.push(rightCamera);
  23039. }
  23040. }
  23041. switch (this.cameraRigMode) {
  23042. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23043. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23044. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23045. break;
  23046. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23047. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23048. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23049. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23050. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23051. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23052. break;
  23053. case Camera.RIG_MODE_VR:
  23054. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23055. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23056. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23057. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23058. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23059. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23060. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23061. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23062. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23063. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23064. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23065. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23066. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23067. if (metrics.compensateDistortion) {
  23068. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23069. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23070. }
  23071. break;
  23072. case Camera.RIG_MODE_WEBVR:
  23073. if (rigParams.vrDisplay) {
  23074. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23075. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23076. //Left eye
  23077. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23078. this._rigCameras[0].setCameraRigParameter("left", true);
  23079. //leaving this for future reference
  23080. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23081. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23082. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23083. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23084. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23085. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23086. this._rigCameras[0].parent = this;
  23087. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23088. //Right eye
  23089. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23090. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23091. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23092. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23093. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23094. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23095. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23096. this._rigCameras[1].parent = this;
  23097. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23098. if (Camera.UseAlternateWebVRRendering) {
  23099. this._rigCameras[1]._skipRendering = true;
  23100. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23101. }
  23102. }
  23103. break;
  23104. }
  23105. this._cascadePostProcessesToRigCams();
  23106. this.update();
  23107. };
  23108. Camera.prototype._getVRProjectionMatrix = function () {
  23109. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23110. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23111. return this._projectionMatrix;
  23112. };
  23113. Camera.prototype._updateCameraRotationMatrix = function () {
  23114. //Here for WebVR
  23115. };
  23116. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23117. //Here for WebVR
  23118. };
  23119. /**
  23120. * This function MUST be overwritten by the different WebVR cameras available.
  23121. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23122. */
  23123. Camera.prototype._getWebVRProjectionMatrix = function () {
  23124. return BABYLON.Matrix.Identity();
  23125. };
  23126. /**
  23127. * This function MUST be overwritten by the different WebVR cameras available.
  23128. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23129. */
  23130. Camera.prototype._getWebVRViewMatrix = function () {
  23131. return BABYLON.Matrix.Identity();
  23132. };
  23133. /** @hidden */
  23134. Camera.prototype.setCameraRigParameter = function (name, value) {
  23135. if (!this._cameraRigParams) {
  23136. this._cameraRigParams = {};
  23137. }
  23138. this._cameraRigParams[name] = value;
  23139. //provisionnally:
  23140. if (name === "interaxialDistance") {
  23141. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23142. }
  23143. };
  23144. /**
  23145. * needs to be overridden by children so sub has required properties to be copied
  23146. * @hidden
  23147. */
  23148. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23149. return null;
  23150. };
  23151. /**
  23152. * May need to be overridden by children
  23153. * @hidden
  23154. */
  23155. Camera.prototype._updateRigCameras = function () {
  23156. for (var i = 0; i < this._rigCameras.length; i++) {
  23157. this._rigCameras[i].minZ = this.minZ;
  23158. this._rigCameras[i].maxZ = this.maxZ;
  23159. this._rigCameras[i].fov = this.fov;
  23160. }
  23161. // only update viewport when ANAGLYPH
  23162. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23163. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23164. }
  23165. };
  23166. /** @hidden */
  23167. Camera.prototype._setupInputs = function () {
  23168. };
  23169. /**
  23170. * Serialiaze the camera setup to a json represention
  23171. * @returns the JSON representation
  23172. */
  23173. Camera.prototype.serialize = function () {
  23174. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23175. // Type
  23176. serializationObject.type = this.getClassName();
  23177. // Parent
  23178. if (this.parent) {
  23179. serializationObject.parentId = this.parent.id;
  23180. }
  23181. if (this.inputs) {
  23182. this.inputs.serialize(serializationObject);
  23183. }
  23184. // Animations
  23185. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23186. serializationObject.ranges = this.serializeAnimationRanges();
  23187. return serializationObject;
  23188. };
  23189. /**
  23190. * Clones the current camera.
  23191. * @param name The cloned camera name
  23192. * @returns the cloned camera
  23193. */
  23194. Camera.prototype.clone = function (name) {
  23195. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23196. };
  23197. /**
  23198. * Gets the direction of the camera relative to a given local axis.
  23199. * @param localAxis Defines the reference axis to provide a relative direction.
  23200. * @return the direction
  23201. */
  23202. Camera.prototype.getDirection = function (localAxis) {
  23203. var result = BABYLON.Vector3.Zero();
  23204. this.getDirectionToRef(localAxis, result);
  23205. return result;
  23206. };
  23207. /**
  23208. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23209. * @param localAxis Defines the reference axis to provide a relative direction.
  23210. * @param result Defines the vector to store the result in
  23211. */
  23212. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23213. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23214. };
  23215. /**
  23216. * Gets a camera constructor for a given camera type
  23217. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23218. * @param name The name of the camera the result will be able to instantiate
  23219. * @param scene The scene the result will construct the camera in
  23220. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23221. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23222. * @returns a factory method to construc the camera
  23223. */
  23224. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23225. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23226. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23227. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23228. interaxial_distance: interaxial_distance,
  23229. isStereoscopicSideBySide: isStereoscopicSideBySide
  23230. });
  23231. if (constructorFunc) {
  23232. return constructorFunc;
  23233. }
  23234. // Default to universal camera
  23235. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23236. };
  23237. /**
  23238. * Compute the world matrix of the camera.
  23239. * @returns the camera workd matrix
  23240. */
  23241. Camera.prototype.computeWorldMatrix = function () {
  23242. return this.getWorldMatrix();
  23243. };
  23244. /**
  23245. * Parse a JSON and creates the camera from the parsed information
  23246. * @param parsedCamera The JSON to parse
  23247. * @param scene The scene to instantiate the camera in
  23248. * @returns the newly constructed camera
  23249. */
  23250. Camera.Parse = function (parsedCamera, scene) {
  23251. var type = parsedCamera.type;
  23252. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23253. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23254. // Parent
  23255. if (parsedCamera.parentId) {
  23256. camera._waitingParentId = parsedCamera.parentId;
  23257. }
  23258. //If camera has an input manager, let it parse inputs settings
  23259. if (camera.inputs) {
  23260. camera.inputs.parse(parsedCamera);
  23261. camera._setupInputs();
  23262. }
  23263. if (camera.setPosition) { // need to force position
  23264. camera.position.copyFromFloats(0, 0, 0);
  23265. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23266. }
  23267. // Target
  23268. if (parsedCamera.target) {
  23269. if (camera.setTarget) {
  23270. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23271. }
  23272. }
  23273. // Apply 3d rig, when found
  23274. if (parsedCamera.cameraRigMode) {
  23275. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23276. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23277. }
  23278. // Animations
  23279. if (parsedCamera.animations) {
  23280. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23281. var parsedAnimation = parsedCamera.animations[animationIndex];
  23282. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23283. }
  23284. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23285. }
  23286. if (parsedCamera.autoAnimate) {
  23287. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23288. }
  23289. return camera;
  23290. };
  23291. /**
  23292. * This is the default projection mode used by the cameras.
  23293. * It helps recreating a feeling of perspective and better appreciate depth.
  23294. * This is the best way to simulate real life cameras.
  23295. */
  23296. Camera.PERSPECTIVE_CAMERA = 0;
  23297. /**
  23298. * This helps creating camera with an orthographic mode.
  23299. * 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.
  23300. */
  23301. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23302. /**
  23303. * This is the default FOV mode for perspective cameras.
  23304. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23305. */
  23306. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23307. /**
  23308. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23309. */
  23310. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23311. /**
  23312. * This specifies ther is no need for a camera rig.
  23313. * Basically only one eye is rendered corresponding to the camera.
  23314. */
  23315. Camera.RIG_MODE_NONE = 0;
  23316. /**
  23317. * Simulates a camera Rig with one blue eye and one red eye.
  23318. * This can be use with 3d blue and red glasses.
  23319. */
  23320. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23321. /**
  23322. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23323. */
  23324. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23325. /**
  23326. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23327. */
  23328. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23329. /**
  23330. * Defines that both eyes of the camera will be rendered over under each other.
  23331. */
  23332. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23333. /**
  23334. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23335. */
  23336. Camera.RIG_MODE_VR = 20;
  23337. /**
  23338. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23339. */
  23340. Camera.RIG_MODE_WEBVR = 21;
  23341. /**
  23342. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23343. */
  23344. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23345. /**
  23346. * @hidden
  23347. * Might be removed once multiview will be a thing
  23348. */
  23349. Camera.UseAlternateWebVRRendering = false;
  23350. __decorate([
  23351. BABYLON.serializeAsVector3()
  23352. ], Camera.prototype, "position", void 0);
  23353. __decorate([
  23354. BABYLON.serializeAsVector3()
  23355. ], Camera.prototype, "upVector", void 0);
  23356. __decorate([
  23357. BABYLON.serialize()
  23358. ], Camera.prototype, "orthoLeft", void 0);
  23359. __decorate([
  23360. BABYLON.serialize()
  23361. ], Camera.prototype, "orthoRight", void 0);
  23362. __decorate([
  23363. BABYLON.serialize()
  23364. ], Camera.prototype, "orthoBottom", void 0);
  23365. __decorate([
  23366. BABYLON.serialize()
  23367. ], Camera.prototype, "orthoTop", void 0);
  23368. __decorate([
  23369. BABYLON.serialize()
  23370. ], Camera.prototype, "fov", void 0);
  23371. __decorate([
  23372. BABYLON.serialize()
  23373. ], Camera.prototype, "minZ", void 0);
  23374. __decorate([
  23375. BABYLON.serialize()
  23376. ], Camera.prototype, "maxZ", void 0);
  23377. __decorate([
  23378. BABYLON.serialize()
  23379. ], Camera.prototype, "inertia", void 0);
  23380. __decorate([
  23381. BABYLON.serialize()
  23382. ], Camera.prototype, "mode", void 0);
  23383. __decorate([
  23384. BABYLON.serialize()
  23385. ], Camera.prototype, "layerMask", void 0);
  23386. __decorate([
  23387. BABYLON.serialize()
  23388. ], Camera.prototype, "fovMode", void 0);
  23389. __decorate([
  23390. BABYLON.serialize()
  23391. ], Camera.prototype, "cameraRigMode", void 0);
  23392. __decorate([
  23393. BABYLON.serialize()
  23394. ], Camera.prototype, "interaxialDistance", void 0);
  23395. __decorate([
  23396. BABYLON.serialize()
  23397. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23398. return Camera;
  23399. }(BABYLON.Node));
  23400. BABYLON.Camera = Camera;
  23401. })(BABYLON || (BABYLON = {}));
  23402. //# sourceMappingURL=babylon.camera.js.map
  23403. var BABYLON;
  23404. (function (BABYLON) {
  23405. /**
  23406. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23407. * It is enable to manage the different groups as well as the different necessary sort functions.
  23408. * This should not be used directly aside of the few static configurations
  23409. */
  23410. var RenderingManager = /** @class */ (function () {
  23411. /**
  23412. * Instantiates a new rendering group for a particular scene
  23413. * @param scene Defines the scene the groups belongs to
  23414. */
  23415. function RenderingManager(scene) {
  23416. /**
  23417. * @hidden
  23418. */
  23419. this._useSceneAutoClearSetup = false;
  23420. this._renderingGroups = new Array();
  23421. this._autoClearDepthStencil = {};
  23422. this._customOpaqueSortCompareFn = {};
  23423. this._customAlphaTestSortCompareFn = {};
  23424. this._customTransparentSortCompareFn = {};
  23425. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23426. this._scene = scene;
  23427. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23428. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23429. }
  23430. }
  23431. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23432. if (depth === void 0) { depth = true; }
  23433. if (stencil === void 0) { stencil = true; }
  23434. if (this._depthStencilBufferAlreadyCleaned) {
  23435. return;
  23436. }
  23437. this._scene.getEngine().clear(null, false, depth, stencil);
  23438. this._depthStencilBufferAlreadyCleaned = true;
  23439. };
  23440. /**
  23441. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  23442. * @hidden
  23443. */
  23444. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23445. // Update the observable context (not null as it only goes away on dispose)
  23446. var info = this._renderingGroupInfo;
  23447. info.scene = this._scene;
  23448. info.camera = this._scene.activeCamera;
  23449. // Dispatch sprites
  23450. if (this._scene.spriteManagers && renderSprites) {
  23451. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23452. var manager = this._scene.spriteManagers[index];
  23453. this.dispatchSprites(manager);
  23454. }
  23455. }
  23456. // Render
  23457. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23458. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23459. var renderingGroup = this._renderingGroups[index];
  23460. if (!renderingGroup)
  23461. continue;
  23462. var renderingGroupMask = Math.pow(2, index);
  23463. info.renderingGroupId = index;
  23464. // Before Observable
  23465. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23466. // Clear depth/stencil if needed
  23467. if (RenderingManager.AUTOCLEAR) {
  23468. var autoClear = this._useSceneAutoClearSetup ?
  23469. this._scene.getAutoClearDepthStencilSetup(index) :
  23470. this._autoClearDepthStencil[index];
  23471. if (autoClear && autoClear.autoClear) {
  23472. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23473. }
  23474. }
  23475. // Render
  23476. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23477. var step = _a[_i];
  23478. step.action(index);
  23479. }
  23480. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23481. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23482. var step = _c[_b];
  23483. step.action(index);
  23484. }
  23485. // After Observable
  23486. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23487. }
  23488. };
  23489. /**
  23490. * Resets the different information of the group to prepare a new frame
  23491. * @hidden
  23492. */
  23493. RenderingManager.prototype.reset = function () {
  23494. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23495. var renderingGroup = this._renderingGroups[index];
  23496. if (renderingGroup) {
  23497. renderingGroup.prepare();
  23498. }
  23499. }
  23500. };
  23501. /**
  23502. * Dispose and release the group and its associated resources.
  23503. * @hidden
  23504. */
  23505. RenderingManager.prototype.dispose = function () {
  23506. this.freeRenderingGroups();
  23507. this._renderingGroups.length = 0;
  23508. this._renderingGroupInfo = null;
  23509. };
  23510. /**
  23511. * Clear the info related to rendering groups preventing retention points during dispose.
  23512. */
  23513. RenderingManager.prototype.freeRenderingGroups = function () {
  23514. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23515. var renderingGroup = this._renderingGroups[index];
  23516. if (renderingGroup) {
  23517. renderingGroup.dispose();
  23518. }
  23519. }
  23520. };
  23521. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23522. if (this._renderingGroups[renderingGroupId] === undefined) {
  23523. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23524. }
  23525. };
  23526. /**
  23527. * Add a sprite manager to the rendering manager in order to render it this frame.
  23528. * @param spriteManager Define the sprite manager to render
  23529. */
  23530. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23531. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23532. this._prepareRenderingGroup(renderingGroupId);
  23533. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23534. };
  23535. /**
  23536. * Add a particle system to the rendering manager in order to render it this frame.
  23537. * @param particleSystem Define the particle system to render
  23538. */
  23539. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23540. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23541. this._prepareRenderingGroup(renderingGroupId);
  23542. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23543. };
  23544. /**
  23545. * Add a submesh to the manager in order to render it this frame
  23546. * @param subMesh The submesh to dispatch
  23547. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23548. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23549. */
  23550. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23551. if (mesh === undefined) {
  23552. mesh = subMesh.getMesh();
  23553. }
  23554. var renderingGroupId = mesh.renderingGroupId || 0;
  23555. this._prepareRenderingGroup(renderingGroupId);
  23556. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23557. };
  23558. /**
  23559. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23560. * This allowed control for front to back rendering or reversly depending of the special needs.
  23561. *
  23562. * @param renderingGroupId The rendering group id corresponding to its index
  23563. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23564. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23565. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23566. */
  23567. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23568. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23569. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23570. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23571. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23572. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23573. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23574. if (this._renderingGroups[renderingGroupId]) {
  23575. var group = this._renderingGroups[renderingGroupId];
  23576. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23577. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23578. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23579. }
  23580. };
  23581. /**
  23582. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23583. *
  23584. * @param renderingGroupId The rendering group id corresponding to its index
  23585. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23586. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23587. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23588. */
  23589. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23590. if (depth === void 0) { depth = true; }
  23591. if (stencil === void 0) { stencil = true; }
  23592. this._autoClearDepthStencil[renderingGroupId] = {
  23593. autoClear: autoClearDepthStencil,
  23594. depth: depth,
  23595. stencil: stencil
  23596. };
  23597. };
  23598. /**
  23599. * Gets the current auto clear configuration for one rendering group of the rendering
  23600. * manager.
  23601. * @param index the rendering group index to get the information for
  23602. * @returns The auto clear setup for the requested rendering group
  23603. */
  23604. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23605. return this._autoClearDepthStencil[index];
  23606. };
  23607. /**
  23608. * The max id used for rendering groups (not included)
  23609. */
  23610. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23611. /**
  23612. * The min id used for rendering groups (included)
  23613. */
  23614. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23615. /**
  23616. * Used to globally prevent autoclearing scenes.
  23617. */
  23618. RenderingManager.AUTOCLEAR = true;
  23619. return RenderingManager;
  23620. }());
  23621. BABYLON.RenderingManager = RenderingManager;
  23622. })(BABYLON || (BABYLON = {}));
  23623. //# sourceMappingURL=babylon.renderingManager.js.map
  23624. var BABYLON;
  23625. (function (BABYLON) {
  23626. /**
  23627. * This represents the object necessary to create a rendering group.
  23628. * This is exclusively used and created by the rendering manager.
  23629. * To modify the behavior, you use the available helpers in your scene or meshes.
  23630. * @hidden
  23631. */
  23632. var RenderingGroup = /** @class */ (function () {
  23633. /**
  23634. * Creates a new rendering group.
  23635. * @param index The rendering group index
  23636. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23637. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23638. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23639. */
  23640. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23641. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23642. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23643. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23644. this.index = index;
  23645. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23646. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23647. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23648. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23649. this._particleSystems = new BABYLON.SmartArray(256);
  23650. this._spriteManagers = new BABYLON.SmartArray(256);
  23651. this._edgesRenderers = new BABYLON.SmartArray(16);
  23652. this._scene = scene;
  23653. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23654. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23655. this.transparentSortCompareFn = transparentSortCompareFn;
  23656. }
  23657. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23658. /**
  23659. * Set the opaque sort comparison function.
  23660. * If null the sub meshes will be render in the order they were created
  23661. */
  23662. set: function (value) {
  23663. this._opaqueSortCompareFn = value;
  23664. if (value) {
  23665. this._renderOpaque = this.renderOpaqueSorted;
  23666. }
  23667. else {
  23668. this._renderOpaque = RenderingGroup.renderUnsorted;
  23669. }
  23670. },
  23671. enumerable: true,
  23672. configurable: true
  23673. });
  23674. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23675. /**
  23676. * Set the alpha test sort comparison function.
  23677. * If null the sub meshes will be render in the order they were created
  23678. */
  23679. set: function (value) {
  23680. this._alphaTestSortCompareFn = value;
  23681. if (value) {
  23682. this._renderAlphaTest = this.renderAlphaTestSorted;
  23683. }
  23684. else {
  23685. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23686. }
  23687. },
  23688. enumerable: true,
  23689. configurable: true
  23690. });
  23691. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23692. /**
  23693. * Set the transparent sort comparison function.
  23694. * If null the sub meshes will be render in the order they were created
  23695. */
  23696. set: function (value) {
  23697. if (value) {
  23698. this._transparentSortCompareFn = value;
  23699. }
  23700. else {
  23701. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23702. }
  23703. this._renderTransparent = this.renderTransparentSorted;
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. /**
  23709. * Render all the sub meshes contained in the group.
  23710. * @param customRenderFunction Used to override the default render behaviour of the group.
  23711. * @returns true if rendered some submeshes.
  23712. */
  23713. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23714. if (customRenderFunction) {
  23715. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23716. return;
  23717. }
  23718. var engine = this._scene.getEngine();
  23719. // Depth only
  23720. if (this._depthOnlySubMeshes.length !== 0) {
  23721. engine.setColorWrite(false);
  23722. this._renderAlphaTest(this._depthOnlySubMeshes);
  23723. engine.setColorWrite(true);
  23724. }
  23725. // Opaque
  23726. if (this._opaqueSubMeshes.length !== 0) {
  23727. this._renderOpaque(this._opaqueSubMeshes);
  23728. }
  23729. // Alpha test
  23730. if (this._alphaTestSubMeshes.length !== 0) {
  23731. this._renderAlphaTest(this._alphaTestSubMeshes);
  23732. }
  23733. var stencilState = engine.getStencilBuffer();
  23734. engine.setStencilBuffer(false);
  23735. // Sprites
  23736. if (renderSprites) {
  23737. this._renderSprites();
  23738. }
  23739. // Particles
  23740. if (renderParticles) {
  23741. this._renderParticles(activeMeshes);
  23742. }
  23743. if (this.onBeforeTransparentRendering) {
  23744. this.onBeforeTransparentRendering();
  23745. }
  23746. // Transparent
  23747. if (this._transparentSubMeshes.length !== 0) {
  23748. this._renderTransparent(this._transparentSubMeshes);
  23749. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23750. }
  23751. // Set back stencil to false in case it changes before the edge renderer.
  23752. engine.setStencilBuffer(false);
  23753. // Edges
  23754. if (this._edgesRenderers.length) {
  23755. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23756. this._edgesRenderers.data[edgesRendererIndex].render();
  23757. }
  23758. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23759. }
  23760. // Restore Stencil state.
  23761. engine.setStencilBuffer(stencilState);
  23762. };
  23763. /**
  23764. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23765. * @param subMeshes The submeshes to render
  23766. */
  23767. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23768. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23769. };
  23770. /**
  23771. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23772. * @param subMeshes The submeshes to render
  23773. */
  23774. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23775. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23776. };
  23777. /**
  23778. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23779. * @param subMeshes The submeshes to render
  23780. */
  23781. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23782. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23783. };
  23784. /**
  23785. * Renders the submeshes in a specified order.
  23786. * @param subMeshes The submeshes to sort before render
  23787. * @param sortCompareFn The comparison function use to sort
  23788. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23789. * @param transparent Specifies to activate blending if true
  23790. */
  23791. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23792. var subIndex = 0;
  23793. var subMesh;
  23794. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23795. for (; subIndex < subMeshes.length; subIndex++) {
  23796. subMesh = subMeshes.data[subIndex];
  23797. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23798. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23799. }
  23800. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23801. if (sortCompareFn) {
  23802. sortedArray.sort(sortCompareFn);
  23803. }
  23804. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23805. subMesh = sortedArray[subIndex];
  23806. if (transparent) {
  23807. var material = subMesh.getMaterial();
  23808. if (material && material.needDepthPrePass) {
  23809. var engine = material.getScene().getEngine();
  23810. engine.setColorWrite(false);
  23811. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23812. subMesh.render(false);
  23813. engine.setColorWrite(true);
  23814. }
  23815. }
  23816. subMesh.render(transparent);
  23817. }
  23818. };
  23819. /**
  23820. * Renders the submeshes in the order they were dispatched (no sort applied).
  23821. * @param subMeshes The submeshes to render
  23822. */
  23823. RenderingGroup.renderUnsorted = function (subMeshes) {
  23824. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23825. var submesh = subMeshes.data[subIndex];
  23826. submesh.render(false);
  23827. }
  23828. };
  23829. /**
  23830. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23831. * are rendered back to front if in the same alpha index.
  23832. *
  23833. * @param a The first submesh
  23834. * @param b The second submesh
  23835. * @returns The result of the comparison
  23836. */
  23837. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23838. // Alpha index first
  23839. if (a._alphaIndex > b._alphaIndex) {
  23840. return 1;
  23841. }
  23842. if (a._alphaIndex < b._alphaIndex) {
  23843. return -1;
  23844. }
  23845. // Then distance to camera
  23846. return RenderingGroup.backToFrontSortCompare(a, b);
  23847. };
  23848. /**
  23849. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23850. * are rendered back to front.
  23851. *
  23852. * @param a The first submesh
  23853. * @param b The second submesh
  23854. * @returns The result of the comparison
  23855. */
  23856. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23857. // Then distance to camera
  23858. if (a._distanceToCamera < b._distanceToCamera) {
  23859. return 1;
  23860. }
  23861. if (a._distanceToCamera > b._distanceToCamera) {
  23862. return -1;
  23863. }
  23864. return 0;
  23865. };
  23866. /**
  23867. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23868. * are rendered front to back (prevent overdraw).
  23869. *
  23870. * @param a The first submesh
  23871. * @param b The second submesh
  23872. * @returns The result of the comparison
  23873. */
  23874. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23875. // Then distance to camera
  23876. if (a._distanceToCamera < b._distanceToCamera) {
  23877. return -1;
  23878. }
  23879. if (a._distanceToCamera > b._distanceToCamera) {
  23880. return 1;
  23881. }
  23882. return 0;
  23883. };
  23884. /**
  23885. * Resets the different lists of submeshes to prepare a new frame.
  23886. */
  23887. RenderingGroup.prototype.prepare = function () {
  23888. this._opaqueSubMeshes.reset();
  23889. this._transparentSubMeshes.reset();
  23890. this._alphaTestSubMeshes.reset();
  23891. this._depthOnlySubMeshes.reset();
  23892. this._particleSystems.reset();
  23893. this._spriteManagers.reset();
  23894. this._edgesRenderers.reset();
  23895. };
  23896. RenderingGroup.prototype.dispose = function () {
  23897. this._opaqueSubMeshes.dispose();
  23898. this._transparentSubMeshes.dispose();
  23899. this._alphaTestSubMeshes.dispose();
  23900. this._depthOnlySubMeshes.dispose();
  23901. this._particleSystems.dispose();
  23902. this._spriteManagers.dispose();
  23903. this._edgesRenderers.dispose();
  23904. };
  23905. /**
  23906. * Inserts the submesh in its correct queue depending on its material.
  23907. * @param subMesh The submesh to dispatch
  23908. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23909. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23910. */
  23911. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23912. // Get mesh and materials if not provided
  23913. if (mesh === undefined) {
  23914. mesh = subMesh.getMesh();
  23915. }
  23916. if (material === undefined) {
  23917. material = subMesh.getMaterial();
  23918. }
  23919. if (material === null || material === undefined) {
  23920. return;
  23921. }
  23922. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23923. this._transparentSubMeshes.push(subMesh);
  23924. }
  23925. else if (material.needAlphaTesting()) { // Alpha test
  23926. if (material.needDepthPrePass) {
  23927. this._depthOnlySubMeshes.push(subMesh);
  23928. }
  23929. this._alphaTestSubMeshes.push(subMesh);
  23930. }
  23931. else {
  23932. if (material.needDepthPrePass) {
  23933. this._depthOnlySubMeshes.push(subMesh);
  23934. }
  23935. this._opaqueSubMeshes.push(subMesh); // Opaque
  23936. }
  23937. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23938. this._edgesRenderers.push(mesh._edgesRenderer);
  23939. }
  23940. };
  23941. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23942. this._spriteManagers.push(spriteManager);
  23943. };
  23944. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23945. this._particleSystems.push(particleSystem);
  23946. };
  23947. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23948. if (this._particleSystems.length === 0) {
  23949. return;
  23950. }
  23951. // Particles
  23952. var activeCamera = this._scene.activeCamera;
  23953. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23954. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23955. var particleSystem = this._particleSystems.data[particleIndex];
  23956. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23957. continue;
  23958. }
  23959. var emitter = particleSystem.emitter;
  23960. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23961. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23962. }
  23963. }
  23964. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23965. };
  23966. RenderingGroup.prototype._renderSprites = function () {
  23967. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23968. return;
  23969. }
  23970. // Sprites
  23971. var activeCamera = this._scene.activeCamera;
  23972. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23973. for (var id = 0; id < this._spriteManagers.length; id++) {
  23974. var spriteManager = this._spriteManagers.data[id];
  23975. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23976. spriteManager.render();
  23977. }
  23978. }
  23979. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23980. };
  23981. return RenderingGroup;
  23982. }());
  23983. BABYLON.RenderingGroup = RenderingGroup;
  23984. })(BABYLON || (BABYLON = {}));
  23985. //# sourceMappingURL=babylon.renderingGroup.js.map
  23986. var BABYLON;
  23987. (function (BABYLON) {
  23988. /**
  23989. * Groups all the scene component constants in one place to ease maintenance.
  23990. * @hidden
  23991. */
  23992. var SceneComponentConstants = /** @class */ (function () {
  23993. function SceneComponentConstants() {
  23994. }
  23995. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23996. SceneComponentConstants.NAME_LAYER = "Layer";
  23997. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23998. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23999. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24000. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24001. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24002. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24003. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24004. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24005. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24006. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24007. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24008. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24009. SceneComponentConstants.NAME_OCTREE = "Octree";
  24010. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24011. SceneComponentConstants.NAME_AUDIO = "Audio";
  24012. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24013. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24014. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24015. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24016. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24017. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24018. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24019. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24020. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24021. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24022. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24023. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24024. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24025. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24026. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24027. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24028. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24029. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24030. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24031. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24032. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24033. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24034. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24035. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24036. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24037. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24038. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24039. return SceneComponentConstants;
  24040. }());
  24041. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24042. /**
  24043. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24044. * @hidden
  24045. */
  24046. var Stage = /** @class */ (function (_super) {
  24047. __extends(Stage, _super);
  24048. /**
  24049. * Hide ctor from the rest of the world.
  24050. * @param items The items to add.
  24051. */
  24052. function Stage(items) {
  24053. return _super.apply(this, items) || this;
  24054. }
  24055. /**
  24056. * Creates a new Stage.
  24057. * @returns A new instance of a Stage
  24058. */
  24059. Stage.Create = function () {
  24060. return Object.create(Stage.prototype);
  24061. };
  24062. /**
  24063. * Registers a step in an ordered way in the targeted stage.
  24064. * @param index Defines the position to register the step in
  24065. * @param component Defines the component attached to the step
  24066. * @param action Defines the action to launch during the step
  24067. */
  24068. Stage.prototype.registerStep = function (index, component, action) {
  24069. var i = 0;
  24070. var maxIndex = Number.MAX_VALUE;
  24071. for (; i < this.length && i < maxIndex; i++) {
  24072. var step = this[i];
  24073. maxIndex = step.index;
  24074. }
  24075. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24076. };
  24077. /**
  24078. * Clears all the steps from the stage.
  24079. */
  24080. Stage.prototype.clear = function () {
  24081. this.length = 0;
  24082. };
  24083. return Stage;
  24084. }(Array));
  24085. BABYLON.Stage = Stage;
  24086. })(BABYLON || (BABYLON = {}));
  24087. //# sourceMappingURL=babylon.sceneComponent.js.map
  24088. var BABYLON;
  24089. (function (BABYLON) {
  24090. /**
  24091. * Base class of the scene acting as a container for the different elements composing a scene.
  24092. * This class is dynamically extended by the different components of the scene increasing
  24093. * flexibility and reducing coupling
  24094. */
  24095. var AbstractScene = /** @class */ (function () {
  24096. function AbstractScene() {
  24097. /**
  24098. * Gets the list of root nodes (ie. nodes with no parent)
  24099. */
  24100. this.rootNodes = new Array();
  24101. /** All of the cameras added to this scene
  24102. * @see http://doc.babylonjs.com/babylon101/cameras
  24103. */
  24104. this.cameras = new Array();
  24105. /**
  24106. * All of the lights added to this scene
  24107. * @see http://doc.babylonjs.com/babylon101/lights
  24108. */
  24109. this.lights = new Array();
  24110. /**
  24111. * All of the (abstract) meshes added to this scene
  24112. */
  24113. this.meshes = new Array();
  24114. /**
  24115. * The list of skeletons added to the scene
  24116. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24117. */
  24118. this.skeletons = new Array();
  24119. /**
  24120. * All of the particle systems added to this scene
  24121. * @see http://doc.babylonjs.com/babylon101/particles
  24122. */
  24123. this.particleSystems = new Array();
  24124. /**
  24125. * Gets a list of Animations associated with the scene
  24126. */
  24127. this.animations = [];
  24128. /**
  24129. * All of the animation groups added to this scene
  24130. * @see http://doc.babylonjs.com/how_to/group
  24131. */
  24132. this.animationGroups = new Array();
  24133. /**
  24134. * All of the multi-materials added to this scene
  24135. * @see http://doc.babylonjs.com/how_to/multi_materials
  24136. */
  24137. this.multiMaterials = new Array();
  24138. /**
  24139. * All of the materials added to this scene
  24140. * @see http://doc.babylonjs.com/babylon101/materials
  24141. */
  24142. this.materials = new Array();
  24143. /**
  24144. * The list of morph target managers added to the scene
  24145. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24146. */
  24147. this.morphTargetManagers = new Array();
  24148. /**
  24149. * The list of geometries used in the scene.
  24150. */
  24151. this.geometries = new Array();
  24152. /**
  24153. * All of the tranform nodes added to this scene
  24154. * @see http://doc.babylonjs.com/how_to/transformnode
  24155. */
  24156. this.transformNodes = new Array();
  24157. /**
  24158. * ActionManagers available on the scene.
  24159. */
  24160. this.actionManagers = new Array();
  24161. /**
  24162. * Textures to keep.
  24163. */
  24164. this.textures = new Array();
  24165. }
  24166. /**
  24167. * Adds a parser in the list of available ones
  24168. * @param name Defines the name of the parser
  24169. * @param parser Defines the parser to add
  24170. */
  24171. AbstractScene.AddParser = function (name, parser) {
  24172. this._BabylonFileParsers[name] = parser;
  24173. };
  24174. /**
  24175. * Gets a general parser from the list of avaialble ones
  24176. * @param name Defines the name of the parser
  24177. * @returns the requested parser or null
  24178. */
  24179. AbstractScene.GetParser = function (name) {
  24180. if (this._BabylonFileParsers[name]) {
  24181. return this._BabylonFileParsers[name];
  24182. }
  24183. return null;
  24184. };
  24185. /**
  24186. * Adds n individual parser in the list of available ones
  24187. * @param name Defines the name of the parser
  24188. * @param parser Defines the parser to add
  24189. */
  24190. AbstractScene.AddIndividualParser = function (name, parser) {
  24191. this._IndividualBabylonFileParsers[name] = parser;
  24192. };
  24193. /**
  24194. * Gets an individual parser from the list of avaialble ones
  24195. * @param name Defines the name of the parser
  24196. * @returns the requested parser or null
  24197. */
  24198. AbstractScene.GetIndividualParser = function (name) {
  24199. if (this._IndividualBabylonFileParsers[name]) {
  24200. return this._IndividualBabylonFileParsers[name];
  24201. }
  24202. return null;
  24203. };
  24204. /**
  24205. * Parser json data and populate both a scene and its associated container object
  24206. * @param jsonData Defines the data to parse
  24207. * @param scene Defines the scene to parse the data for
  24208. * @param container Defines the container attached to the parsing sequence
  24209. * @param rootUrl Defines the root url of the data
  24210. */
  24211. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24212. for (var parserName in this._BabylonFileParsers) {
  24213. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24214. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24215. }
  24216. }
  24217. };
  24218. /**
  24219. * Stores the list of available parsers in the application.
  24220. */
  24221. AbstractScene._BabylonFileParsers = {};
  24222. /**
  24223. * Stores the list of available individual parsers in the application.
  24224. */
  24225. AbstractScene._IndividualBabylonFileParsers = {};
  24226. return AbstractScene;
  24227. }());
  24228. BABYLON.AbstractScene = AbstractScene;
  24229. })(BABYLON || (BABYLON = {}));
  24230. //# sourceMappingURL=babylon.abstractScene.js.map
  24231. var BABYLON;
  24232. (function (BABYLON) {
  24233. /** @hidden */
  24234. var ClickInfo = /** @class */ (function () {
  24235. function ClickInfo() {
  24236. this._singleClick = false;
  24237. this._doubleClick = false;
  24238. this._hasSwiped = false;
  24239. this._ignore = false;
  24240. }
  24241. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24242. get: function () {
  24243. return this._singleClick;
  24244. },
  24245. set: function (b) {
  24246. this._singleClick = b;
  24247. },
  24248. enumerable: true,
  24249. configurable: true
  24250. });
  24251. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24252. get: function () {
  24253. return this._doubleClick;
  24254. },
  24255. set: function (b) {
  24256. this._doubleClick = b;
  24257. },
  24258. enumerable: true,
  24259. configurable: true
  24260. });
  24261. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24262. get: function () {
  24263. return this._hasSwiped;
  24264. },
  24265. set: function (b) {
  24266. this._hasSwiped = b;
  24267. },
  24268. enumerable: true,
  24269. configurable: true
  24270. });
  24271. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24272. get: function () {
  24273. return this._ignore;
  24274. },
  24275. set: function (b) {
  24276. this._ignore = b;
  24277. },
  24278. enumerable: true,
  24279. configurable: true
  24280. });
  24281. return ClickInfo;
  24282. }());
  24283. /**
  24284. * This class is used by the onRenderingGroupObservable
  24285. */
  24286. var RenderingGroupInfo = /** @class */ (function () {
  24287. function RenderingGroupInfo() {
  24288. }
  24289. return RenderingGroupInfo;
  24290. }());
  24291. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24292. /**
  24293. * Represents a scene to be rendered by the engine.
  24294. * @see http://doc.babylonjs.com/features/scene
  24295. */
  24296. var Scene = /** @class */ (function (_super) {
  24297. __extends(Scene, _super);
  24298. /**
  24299. * Creates a new Scene
  24300. * @param engine defines the engine to use to render this scene
  24301. */
  24302. function Scene(engine) {
  24303. var _this = _super.call(this) || this;
  24304. // Members
  24305. /**
  24306. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24307. */
  24308. _this.autoClear = true;
  24309. /**
  24310. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24311. */
  24312. _this.autoClearDepthAndStencil = true;
  24313. /**
  24314. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24315. */
  24316. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24317. /**
  24318. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24319. */
  24320. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24321. _this._forceWireframe = false;
  24322. _this._forcePointsCloud = false;
  24323. /**
  24324. * Gets or sets a boolean indicating if animations are enabled
  24325. */
  24326. _this.animationsEnabled = true;
  24327. _this._animationPropertiesOverride = null;
  24328. /**
  24329. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24330. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24331. */
  24332. _this.useConstantAnimationDeltaTime = false;
  24333. /**
  24334. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24335. * Please note that it requires to run a ray cast through the scene on every frame
  24336. */
  24337. _this.constantlyUpdateMeshUnderPointer = false;
  24338. /**
  24339. * Defines the HTML cursor to use when hovering over interactive elements
  24340. */
  24341. _this.hoverCursor = "pointer";
  24342. /**
  24343. * Defines the HTML default cursor to use (empty by default)
  24344. */
  24345. _this.defaultCursor = "";
  24346. /**
  24347. * This is used to call preventDefault() on pointer down
  24348. * in order to block unwanted artifacts like system double clicks
  24349. */
  24350. _this.preventDefaultOnPointerDown = true;
  24351. // Metadata
  24352. /**
  24353. * Gets or sets user defined metadata
  24354. */
  24355. _this.metadata = null;
  24356. /**
  24357. * Use this array to add regular expressions used to disable offline support for specific urls
  24358. */
  24359. _this.disableOfflineSupportExceptionRules = new Array();
  24360. /**
  24361. * An event triggered when the scene is disposed.
  24362. */
  24363. _this.onDisposeObservable = new BABYLON.Observable();
  24364. _this._onDisposeObserver = null;
  24365. /**
  24366. * An event triggered before rendering the scene (right after animations and physics)
  24367. */
  24368. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24369. _this._onBeforeRenderObserver = null;
  24370. /**
  24371. * An event triggered after rendering the scene
  24372. */
  24373. _this.onAfterRenderObservable = new BABYLON.Observable();
  24374. _this._onAfterRenderObserver = null;
  24375. /**
  24376. * An event triggered before animating the scene
  24377. */
  24378. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24379. /**
  24380. * An event triggered after animations processing
  24381. */
  24382. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24383. /**
  24384. * An event triggered before draw calls are ready to be sent
  24385. */
  24386. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24387. /**
  24388. * An event triggered after draw calls have been sent
  24389. */
  24390. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24391. /**
  24392. * An event triggered when the scene is ready
  24393. */
  24394. _this.onReadyObservable = new BABYLON.Observable();
  24395. /**
  24396. * An event triggered before rendering a camera
  24397. */
  24398. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24399. _this._onBeforeCameraRenderObserver = null;
  24400. /**
  24401. * An event triggered after rendering a camera
  24402. */
  24403. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24404. _this._onAfterCameraRenderObserver = null;
  24405. /**
  24406. * An event triggered when active meshes evaluation is about to start
  24407. */
  24408. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24409. /**
  24410. * An event triggered when active meshes evaluation is done
  24411. */
  24412. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24413. /**
  24414. * An event triggered when particles rendering is about to start
  24415. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24416. */
  24417. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24418. /**
  24419. * An event triggered when particles rendering is done
  24420. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24421. */
  24422. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24423. /**
  24424. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24425. */
  24426. _this.onDataLoadedObservable = new BABYLON.Observable();
  24427. /**
  24428. * An event triggered when a camera is created
  24429. */
  24430. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24431. /**
  24432. * An event triggered when a camera is removed
  24433. */
  24434. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24435. /**
  24436. * An event triggered when a light is created
  24437. */
  24438. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24439. /**
  24440. * An event triggered when a light is removed
  24441. */
  24442. _this.onLightRemovedObservable = new BABYLON.Observable();
  24443. /**
  24444. * An event triggered when a geometry is created
  24445. */
  24446. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24447. /**
  24448. * An event triggered when a geometry is removed
  24449. */
  24450. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24451. /**
  24452. * An event triggered when a transform node is created
  24453. */
  24454. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24455. /**
  24456. * An event triggered when a transform node is removed
  24457. */
  24458. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24459. /**
  24460. * An event triggered when a mesh is created
  24461. */
  24462. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24463. /**
  24464. * An event triggered when a mesh is removed
  24465. */
  24466. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24467. /**
  24468. * An event triggered when a material is created
  24469. */
  24470. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  24471. /**
  24472. * An event triggered when a material is removed
  24473. */
  24474. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  24475. /**
  24476. * An event triggered when a texture is created
  24477. */
  24478. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  24479. /**
  24480. * An event triggered when a texture is removed
  24481. */
  24482. _this.onTextureRemovedObservable = new BABYLON.Observable();
  24483. /**
  24484. * An event triggered when render targets are about to be rendered
  24485. * Can happen multiple times per frame.
  24486. */
  24487. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24488. /**
  24489. * An event triggered when render targets were rendered.
  24490. * Can happen multiple times per frame.
  24491. */
  24492. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24493. /**
  24494. * An event triggered before calculating deterministic simulation step
  24495. */
  24496. _this.onBeforeStepObservable = new BABYLON.Observable();
  24497. /**
  24498. * An event triggered after calculating deterministic simulation step
  24499. */
  24500. _this.onAfterStepObservable = new BABYLON.Observable();
  24501. /**
  24502. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24503. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24504. * 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)
  24505. */
  24506. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24507. /**
  24508. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24509. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24510. * 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)
  24511. */
  24512. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24513. /**
  24514. * This Observable will when a mesh has been imported into the scene.
  24515. */
  24516. _this.onMeshImportedObservable = new BABYLON.Observable();
  24517. // Animations
  24518. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24519. /**
  24520. * 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).
  24521. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24522. */
  24523. _this.onPrePointerObservable = new BABYLON.Observable();
  24524. /**
  24525. * Observable event triggered each time an input event is received from the rendering canvas
  24526. */
  24527. _this.onPointerObservable = new BABYLON.Observable();
  24528. _this._meshPickProceed = false;
  24529. _this._currentPickResult = null;
  24530. _this._previousPickResult = null;
  24531. _this._totalPointersPressed = 0;
  24532. _this._doubleClickOccured = false;
  24533. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24534. _this.cameraToUseForPointers = null;
  24535. _this._pointerX = 0;
  24536. _this._pointerY = 0;
  24537. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24538. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24539. _this._startingPointerTime = 0;
  24540. _this._previousStartingPointerTime = 0;
  24541. _this._pointerCaptures = {};
  24542. // Deterministic lockstep
  24543. _this._timeAccumulator = 0;
  24544. _this._currentStepId = 0;
  24545. _this._currentInternalStep = 0;
  24546. // Keyboard
  24547. /**
  24548. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24549. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24550. */
  24551. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24552. /**
  24553. * Observable event triggered each time an keyboard event is received from the hosting window
  24554. */
  24555. _this.onKeyboardObservable = new BABYLON.Observable();
  24556. // Coordinates system
  24557. _this._useRightHandedSystem = false;
  24558. // Fog
  24559. _this._fogEnabled = true;
  24560. _this._fogMode = Scene.FOGMODE_NONE;
  24561. /**
  24562. * Gets or sets the fog color to use
  24563. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24564. */
  24565. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24566. /**
  24567. * Gets or sets the fog density to use
  24568. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24569. */
  24570. _this.fogDensity = 0.1;
  24571. /**
  24572. * Gets or sets the fog start distance to use
  24573. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24574. */
  24575. _this.fogStart = 0;
  24576. /**
  24577. * Gets or sets the fog end distance to use
  24578. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24579. */
  24580. _this.fogEnd = 1000.0;
  24581. // Lights
  24582. _this._shadowsEnabled = true;
  24583. _this._lightsEnabled = true;
  24584. /** All of the active cameras added to this scene. */
  24585. _this.activeCameras = new Array();
  24586. // Textures
  24587. _this._texturesEnabled = true;
  24588. // Particles
  24589. /**
  24590. * Gets or sets a boolean indicating if particles are enabled on this scene
  24591. */
  24592. _this.particlesEnabled = true;
  24593. // Sprites
  24594. /**
  24595. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24596. */
  24597. _this.spritesEnabled = true;
  24598. // Skeletons
  24599. _this._skeletonsEnabled = true;
  24600. // Lens flares
  24601. /**
  24602. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24603. */
  24604. _this.lensFlaresEnabled = true;
  24605. // Collisions
  24606. /**
  24607. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24608. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24609. */
  24610. _this.collisionsEnabled = true;
  24611. /**
  24612. * Defines the gravity applied to this scene (used only for collisions)
  24613. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24614. */
  24615. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24616. // Postprocesses
  24617. /**
  24618. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24619. */
  24620. _this.postProcessesEnabled = true;
  24621. /**
  24622. * The list of postprocesses added to the scene
  24623. */
  24624. _this.postProcesses = new Array();
  24625. // Customs render targets
  24626. /**
  24627. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24628. */
  24629. _this.renderTargetsEnabled = true;
  24630. /**
  24631. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24632. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24633. */
  24634. _this.dumpNextRenderTargets = false;
  24635. /**
  24636. * The list of user defined render targets added to the scene
  24637. */
  24638. _this.customRenderTargets = new Array();
  24639. /**
  24640. * Gets the list of meshes imported to the scene through SceneLoader
  24641. */
  24642. _this.importedMeshesFiles = new Array();
  24643. // Probes
  24644. /**
  24645. * Gets or sets a boolean indicating if probes are enabled on this scene
  24646. */
  24647. _this.probesEnabled = true;
  24648. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24649. // Procedural textures
  24650. /**
  24651. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24652. */
  24653. _this.proceduralTexturesEnabled = true;
  24654. // Performance counters
  24655. _this._totalVertices = new BABYLON.PerfCounter();
  24656. /** @hidden */
  24657. _this._activeIndices = new BABYLON.PerfCounter();
  24658. /** @hidden */
  24659. _this._activeParticles = new BABYLON.PerfCounter();
  24660. /** @hidden */
  24661. _this._activeBones = new BABYLON.PerfCounter();
  24662. _this._animationTime = 0;
  24663. /**
  24664. * Gets or sets a general scale for animation speed
  24665. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24666. */
  24667. _this.animationTimeScale = 1;
  24668. _this._renderId = 0;
  24669. _this._frameId = 0;
  24670. _this._executeWhenReadyTimeoutId = -1;
  24671. _this._intermediateRendering = false;
  24672. _this._viewUpdateFlag = -1;
  24673. _this._projectionUpdateFlag = -1;
  24674. _this._alternateViewUpdateFlag = -1;
  24675. _this._alternateProjectionUpdateFlag = -1;
  24676. /** @hidden */
  24677. _this._toBeDisposed = new Array(256);
  24678. _this._activeRequests = new Array();
  24679. _this._pendingData = new Array();
  24680. _this._isDisposed = false;
  24681. /**
  24682. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24683. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24684. */
  24685. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24686. _this._activeMeshes = new BABYLON.SmartArray(256);
  24687. _this._processedMaterials = new BABYLON.SmartArray(256);
  24688. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24689. /** @hidden */
  24690. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24691. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24692. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24693. /** @hidden */
  24694. _this._activeAnimatables = new Array();
  24695. _this._transformMatrix = BABYLON.Matrix.Zero();
  24696. _this._useAlternateCameraConfiguration = false;
  24697. _this._alternateRendering = false;
  24698. /**
  24699. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24700. * This is useful if there are more lights that the maximum simulteanous authorized
  24701. */
  24702. _this.requireLightSorting = false;
  24703. /**
  24704. * @hidden
  24705. * Backing store of defined scene components.
  24706. */
  24707. _this._components = [];
  24708. /**
  24709. * @hidden
  24710. * Backing store of defined scene components.
  24711. */
  24712. _this._serializableComponents = [];
  24713. /**
  24714. * List of components to register on the next registration step.
  24715. */
  24716. _this._transientComponents = [];
  24717. /**
  24718. * @hidden
  24719. * Defines the actions happening before camera updates.
  24720. */
  24721. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24722. /**
  24723. * @hidden
  24724. * Defines the actions happening before clear the canvas.
  24725. */
  24726. _this._beforeClearStage = BABYLON.Stage.Create();
  24727. /**
  24728. * @hidden
  24729. * Defines the actions when collecting render targets for the frame.
  24730. */
  24731. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24732. /**
  24733. * @hidden
  24734. * Defines the actions happening for one camera in the frame.
  24735. */
  24736. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24737. /**
  24738. * @hidden
  24739. * Defines the actions happening during the per mesh ready checks.
  24740. */
  24741. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24742. /**
  24743. * @hidden
  24744. * Defines the actions happening before evaluate active mesh checks.
  24745. */
  24746. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24747. /**
  24748. * @hidden
  24749. * Defines the actions happening during the evaluate sub mesh checks.
  24750. */
  24751. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24752. /**
  24753. * @hidden
  24754. * Defines the actions happening during the active mesh stage.
  24755. */
  24756. _this._activeMeshStage = BABYLON.Stage.Create();
  24757. /**
  24758. * @hidden
  24759. * Defines the actions happening during the per camera render target step.
  24760. */
  24761. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24762. /**
  24763. * @hidden
  24764. * Defines the actions happening just before the active camera is drawing.
  24765. */
  24766. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24767. /**
  24768. * @hidden
  24769. * Defines the actions happening just before a rendering group is drawing.
  24770. */
  24771. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24772. /**
  24773. * @hidden
  24774. * Defines the actions happening just before a mesh is drawing.
  24775. */
  24776. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24777. /**
  24778. * @hidden
  24779. * Defines the actions happening just after a mesh has been drawn.
  24780. */
  24781. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24782. /**
  24783. * @hidden
  24784. * Defines the actions happening just after a rendering group has been drawn.
  24785. */
  24786. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24787. /**
  24788. * @hidden
  24789. * Defines the actions happening just after the active camera has been drawn.
  24790. */
  24791. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24792. /**
  24793. * @hidden
  24794. * Defines the actions happening just after rendering all cameras and computing intersections.
  24795. */
  24796. _this._afterRenderStage = BABYLON.Stage.Create();
  24797. /**
  24798. * @hidden
  24799. * Defines the actions happening when a pointer move event happens.
  24800. */
  24801. _this._pointerMoveStage = BABYLON.Stage.Create();
  24802. /**
  24803. * @hidden
  24804. * Defines the actions happening when a pointer down event happens.
  24805. */
  24806. _this._pointerDownStage = BABYLON.Stage.Create();
  24807. /**
  24808. * @hidden
  24809. * Defines the actions happening when a pointer up event happens.
  24810. */
  24811. _this._pointerUpStage = BABYLON.Stage.Create();
  24812. _this._defaultMeshCandidates = {
  24813. data: [],
  24814. length: 0
  24815. };
  24816. _this._defaultSubMeshCandidates = {
  24817. data: [],
  24818. length: 0
  24819. };
  24820. _this._activeMeshesFrozen = false;
  24821. /** @hidden */
  24822. _this._allowPostProcessClearColor = true;
  24823. /**
  24824. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24825. */
  24826. _this.getDeterministicFrameTime = function () {
  24827. return 1000.0 / 60.0; // frame time in ms
  24828. };
  24829. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24830. _this._blockMaterialDirtyMechanism = false;
  24831. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24832. _this._engine.scenes.push(_this);
  24833. _this._uid = null;
  24834. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24835. if (BABYLON.PostProcessManager) {
  24836. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24837. }
  24838. if (BABYLON.Tools.IsWindowObjectExist()) {
  24839. _this.attachControl();
  24840. }
  24841. //collision coordinator initialization. For now legacy per default.
  24842. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24843. // Uniform Buffer
  24844. _this._createUbo();
  24845. // Default Image processing definition
  24846. if (BABYLON.ImageProcessingConfiguration) {
  24847. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24848. }
  24849. _this.setDefaultCandidateProviders();
  24850. return _this;
  24851. }
  24852. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24853. /**
  24854. * Texture used in all pbr material as the reflection texture.
  24855. * As in the majority of the scene they are the same (exception for multi room and so on),
  24856. * this is easier to reference from here than from all the materials.
  24857. */
  24858. get: function () {
  24859. return this._environmentTexture;
  24860. },
  24861. /**
  24862. * Texture used in all pbr material as the reflection texture.
  24863. * As in the majority of the scene they are the same (exception for multi room and so on),
  24864. * this is easier to set here than in all the materials.
  24865. */
  24866. set: function (value) {
  24867. if (this._environmentTexture === value) {
  24868. return;
  24869. }
  24870. this._environmentTexture = value;
  24871. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24877. /**
  24878. * Default image processing configuration used either in the rendering
  24879. * Forward main pass or through the imageProcessingPostProcess if present.
  24880. * As in the majority of the scene they are the same (exception for multi camera),
  24881. * this is easier to reference from here than from all the materials and post process.
  24882. *
  24883. * No setter as we it is a shared configuration, you can set the values instead.
  24884. */
  24885. get: function () {
  24886. return this._imageProcessingConfiguration;
  24887. },
  24888. enumerable: true,
  24889. configurable: true
  24890. });
  24891. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24892. get: function () {
  24893. return this._forceWireframe;
  24894. },
  24895. /**
  24896. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24897. */
  24898. set: function (value) {
  24899. if (this._forceWireframe === value) {
  24900. return;
  24901. }
  24902. this._forceWireframe = value;
  24903. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24904. },
  24905. enumerable: true,
  24906. configurable: true
  24907. });
  24908. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24909. get: function () {
  24910. return this._forcePointsCloud;
  24911. },
  24912. /**
  24913. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24914. */
  24915. set: function (value) {
  24916. if (this._forcePointsCloud === value) {
  24917. return;
  24918. }
  24919. this._forcePointsCloud = value;
  24920. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24926. /**
  24927. * Gets or sets the animation properties override
  24928. */
  24929. get: function () {
  24930. return this._animationPropertiesOverride;
  24931. },
  24932. set: function (value) {
  24933. this._animationPropertiesOverride = value;
  24934. },
  24935. enumerable: true,
  24936. configurable: true
  24937. });
  24938. Object.defineProperty(Scene.prototype, "onDispose", {
  24939. /** Sets a function to be executed when this scene is disposed. */
  24940. set: function (callback) {
  24941. if (this._onDisposeObserver) {
  24942. this.onDisposeObservable.remove(this._onDisposeObserver);
  24943. }
  24944. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. Object.defineProperty(Scene.prototype, "beforeRender", {
  24950. /** Sets a function to be executed before rendering this scene */
  24951. set: function (callback) {
  24952. if (this._onBeforeRenderObserver) {
  24953. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24954. }
  24955. if (callback) {
  24956. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24957. }
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. Object.defineProperty(Scene.prototype, "afterRender", {
  24963. /** Sets a function to be executed after rendering this scene */
  24964. set: function (callback) {
  24965. if (this._onAfterRenderObserver) {
  24966. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24967. }
  24968. if (callback) {
  24969. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24970. }
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24976. /** Sets a function to be executed before rendering a camera*/
  24977. set: function (callback) {
  24978. if (this._onBeforeCameraRenderObserver) {
  24979. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24980. }
  24981. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24982. },
  24983. enumerable: true,
  24984. configurable: true
  24985. });
  24986. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24987. /** Sets a function to be executed after rendering a camera*/
  24988. set: function (callback) {
  24989. if (this._onAfterCameraRenderObserver) {
  24990. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24991. }
  24992. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24998. /**
  24999. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25000. */
  25001. get: function () {
  25002. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25008. get: function () {
  25009. return this._useRightHandedSystem;
  25010. },
  25011. /**
  25012. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25013. */
  25014. set: function (value) {
  25015. if (this._useRightHandedSystem === value) {
  25016. return;
  25017. }
  25018. this._useRightHandedSystem = value;
  25019. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25020. },
  25021. enumerable: true,
  25022. configurable: true
  25023. });
  25024. /**
  25025. * Sets the step Id used by deterministic lock step
  25026. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25027. * @param newStepId defines the step Id
  25028. */
  25029. Scene.prototype.setStepId = function (newStepId) {
  25030. this._currentStepId = newStepId;
  25031. };
  25032. ;
  25033. /**
  25034. * Gets the step Id used by deterministic lock step
  25035. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25036. * @returns the step Id
  25037. */
  25038. Scene.prototype.getStepId = function () {
  25039. return this._currentStepId;
  25040. };
  25041. ;
  25042. /**
  25043. * Gets the internal step used by deterministic lock step
  25044. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25045. * @returns the internal step
  25046. */
  25047. Scene.prototype.getInternalStep = function () {
  25048. return this._currentInternalStep;
  25049. };
  25050. ;
  25051. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25052. get: function () {
  25053. return this._fogEnabled;
  25054. },
  25055. /**
  25056. * Gets or sets a boolean indicating if fog is enabled on this scene
  25057. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25058. */
  25059. set: function (value) {
  25060. if (this._fogEnabled === value) {
  25061. return;
  25062. }
  25063. this._fogEnabled = value;
  25064. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25065. },
  25066. enumerable: true,
  25067. configurable: true
  25068. });
  25069. Object.defineProperty(Scene.prototype, "fogMode", {
  25070. get: function () {
  25071. return this._fogMode;
  25072. },
  25073. /**
  25074. * Gets or sets the fog mode to use
  25075. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25076. */
  25077. set: function (value) {
  25078. if (this._fogMode === value) {
  25079. return;
  25080. }
  25081. this._fogMode = value;
  25082. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25083. },
  25084. enumerable: true,
  25085. configurable: true
  25086. });
  25087. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25088. get: function () {
  25089. return this._shadowsEnabled;
  25090. },
  25091. /**
  25092. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25093. */
  25094. set: function (value) {
  25095. if (this._shadowsEnabled === value) {
  25096. return;
  25097. }
  25098. this._shadowsEnabled = value;
  25099. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25100. },
  25101. enumerable: true,
  25102. configurable: true
  25103. });
  25104. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25105. get: function () {
  25106. return this._lightsEnabled;
  25107. },
  25108. /**
  25109. * Gets or sets a boolean indicating if lights are enabled on this scene
  25110. */
  25111. set: function (value) {
  25112. if (this._lightsEnabled === value) {
  25113. return;
  25114. }
  25115. this._lightsEnabled = value;
  25116. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25117. },
  25118. enumerable: true,
  25119. configurable: true
  25120. });
  25121. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25122. /** The default material used on meshes when no material is affected */
  25123. get: function () {
  25124. if (!this._defaultMaterial) {
  25125. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25126. }
  25127. return this._defaultMaterial;
  25128. },
  25129. /** The default material used on meshes when no material is affected */
  25130. set: function (value) {
  25131. this._defaultMaterial = value;
  25132. },
  25133. enumerable: true,
  25134. configurable: true
  25135. });
  25136. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25137. get: function () {
  25138. return this._texturesEnabled;
  25139. },
  25140. /**
  25141. * Gets or sets a boolean indicating if textures are enabled on this scene
  25142. */
  25143. set: function (value) {
  25144. if (this._texturesEnabled === value) {
  25145. return;
  25146. }
  25147. this._texturesEnabled = value;
  25148. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25149. },
  25150. enumerable: true,
  25151. configurable: true
  25152. });
  25153. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25154. get: function () {
  25155. return this._skeletonsEnabled;
  25156. },
  25157. /**
  25158. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25159. */
  25160. set: function (value) {
  25161. if (this._skeletonsEnabled === value) {
  25162. return;
  25163. }
  25164. this._skeletonsEnabled = value;
  25165. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25166. },
  25167. enumerable: true,
  25168. configurable: true
  25169. });
  25170. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25171. /** @hidden */
  25172. get: function () {
  25173. return this._alternateRendering;
  25174. },
  25175. enumerable: true,
  25176. configurable: true
  25177. });
  25178. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25179. /**
  25180. * Gets the list of frustum planes (built from the active camera)
  25181. */
  25182. get: function () {
  25183. return this._frustumPlanes;
  25184. },
  25185. enumerable: true,
  25186. configurable: true
  25187. });
  25188. /**
  25189. * Registers the transient components if needed.
  25190. */
  25191. Scene.prototype._registerTransientComponents = function () {
  25192. // Register components that have been associated lately to the scene.
  25193. if (this._transientComponents.length > 0) {
  25194. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25195. var component = _a[_i];
  25196. component.register();
  25197. }
  25198. this._transientComponents = [];
  25199. }
  25200. };
  25201. /**
  25202. * @hidden
  25203. * Add a component to the scene.
  25204. * Note that the ccomponent could be registered on th next frame if this is called after
  25205. * the register component stage.
  25206. * @param component Defines the component to add to the scene
  25207. */
  25208. Scene.prototype._addComponent = function (component) {
  25209. this._components.push(component);
  25210. this._transientComponents.push(component);
  25211. var serializableComponent = component;
  25212. if (serializableComponent.addFromContainer) {
  25213. this._serializableComponents.push(serializableComponent);
  25214. }
  25215. };
  25216. /**
  25217. * @hidden
  25218. * Gets a component from the scene.
  25219. * @param name defines the name of the component to retrieve
  25220. * @returns the component or null if not present
  25221. */
  25222. Scene.prototype._getComponent = function (name) {
  25223. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25224. var component = _a[_i];
  25225. if (component.name === name) {
  25226. return component;
  25227. }
  25228. }
  25229. return null;
  25230. };
  25231. /**
  25232. * @hidden
  25233. */
  25234. Scene.prototype._getDefaultMeshCandidates = function () {
  25235. this._defaultMeshCandidates.data = this.meshes;
  25236. this._defaultMeshCandidates.length = this.meshes.length;
  25237. return this._defaultMeshCandidates;
  25238. };
  25239. /**
  25240. * @hidden
  25241. */
  25242. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25243. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25244. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25245. return this._defaultSubMeshCandidates;
  25246. };
  25247. /**
  25248. * Sets the default candidate providers for the scene.
  25249. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25250. * and getCollidingSubMeshCandidates to their default function
  25251. */
  25252. Scene.prototype.setDefaultCandidateProviders = function () {
  25253. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25254. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25255. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25256. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25257. };
  25258. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25259. /**
  25260. * Gets a boolean indicating if collisions are processed on a web worker
  25261. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25262. */
  25263. get: function () {
  25264. return this._workerCollisions;
  25265. },
  25266. set: function (enabled) {
  25267. if (!BABYLON.CollisionCoordinatorLegacy) {
  25268. return;
  25269. }
  25270. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25271. this._workerCollisions = enabled;
  25272. if (this.collisionCoordinator) {
  25273. this.collisionCoordinator.destroy();
  25274. }
  25275. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25276. this.collisionCoordinator.init(this);
  25277. },
  25278. enumerable: true,
  25279. configurable: true
  25280. });
  25281. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25282. /**
  25283. * Gets the mesh that is currently under the pointer
  25284. */
  25285. get: function () {
  25286. return this._pointerOverMesh;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. Object.defineProperty(Scene.prototype, "pointerX", {
  25292. /**
  25293. * Gets the current on-screen X position of the pointer
  25294. */
  25295. get: function () {
  25296. return this._pointerX;
  25297. },
  25298. enumerable: true,
  25299. configurable: true
  25300. });
  25301. Object.defineProperty(Scene.prototype, "pointerY", {
  25302. /**
  25303. * Gets the current on-screen Y position of the pointer
  25304. */
  25305. get: function () {
  25306. return this._pointerY;
  25307. },
  25308. enumerable: true,
  25309. configurable: true
  25310. });
  25311. /**
  25312. * Gets the cached material (ie. the latest rendered one)
  25313. * @returns the cached material
  25314. */
  25315. Scene.prototype.getCachedMaterial = function () {
  25316. return this._cachedMaterial;
  25317. };
  25318. /**
  25319. * Gets the cached effect (ie. the latest rendered one)
  25320. * @returns the cached effect
  25321. */
  25322. Scene.prototype.getCachedEffect = function () {
  25323. return this._cachedEffect;
  25324. };
  25325. /**
  25326. * Gets the cached visibility state (ie. the latest rendered one)
  25327. * @returns the cached visibility state
  25328. */
  25329. Scene.prototype.getCachedVisibility = function () {
  25330. return this._cachedVisibility;
  25331. };
  25332. /**
  25333. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25334. * @param material defines the current material
  25335. * @param effect defines the current effect
  25336. * @param visibility defines the current visibility state
  25337. * @returns true if one parameter is not cached
  25338. */
  25339. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25340. if (visibility === void 0) { visibility = 1; }
  25341. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25342. };
  25343. /**
  25344. * Gets the engine associated with the scene
  25345. * @returns an Engine
  25346. */
  25347. Scene.prototype.getEngine = function () {
  25348. return this._engine;
  25349. };
  25350. /**
  25351. * Gets the total number of vertices rendered per frame
  25352. * @returns the total number of vertices rendered per frame
  25353. */
  25354. Scene.prototype.getTotalVertices = function () {
  25355. return this._totalVertices.current;
  25356. };
  25357. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25358. /**
  25359. * Gets the performance counter for total vertices
  25360. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25361. */
  25362. get: function () {
  25363. return this._totalVertices;
  25364. },
  25365. enumerable: true,
  25366. configurable: true
  25367. });
  25368. /**
  25369. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25370. * @returns the total number of active indices rendered per frame
  25371. */
  25372. Scene.prototype.getActiveIndices = function () {
  25373. return this._activeIndices.current;
  25374. };
  25375. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25376. /**
  25377. * Gets the performance counter for active indices
  25378. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25379. */
  25380. get: function () {
  25381. return this._activeIndices;
  25382. },
  25383. enumerable: true,
  25384. configurable: true
  25385. });
  25386. /**
  25387. * Gets the total number of active particles rendered per frame
  25388. * @returns the total number of active particles rendered per frame
  25389. */
  25390. Scene.prototype.getActiveParticles = function () {
  25391. return this._activeParticles.current;
  25392. };
  25393. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25394. /**
  25395. * Gets the performance counter for active particles
  25396. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25397. */
  25398. get: function () {
  25399. return this._activeParticles;
  25400. },
  25401. enumerable: true,
  25402. configurable: true
  25403. });
  25404. /**
  25405. * Gets the total number of active bones rendered per frame
  25406. * @returns the total number of active bones rendered per frame
  25407. */
  25408. Scene.prototype.getActiveBones = function () {
  25409. return this._activeBones.current;
  25410. };
  25411. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25412. /**
  25413. * Gets the performance counter for active bones
  25414. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25415. */
  25416. get: function () {
  25417. return this._activeBones;
  25418. },
  25419. enumerable: true,
  25420. configurable: true
  25421. });
  25422. /** @hidden */
  25423. Scene.prototype.getInterFramePerfCounter = function () {
  25424. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25425. return 0;
  25426. };
  25427. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25428. /** @hidden */
  25429. get: function () {
  25430. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25431. return null;
  25432. },
  25433. enumerable: true,
  25434. configurable: true
  25435. });
  25436. /** @hidden */
  25437. Scene.prototype.getLastFrameDuration = function () {
  25438. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25439. return 0;
  25440. };
  25441. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25442. /** @hidden */
  25443. get: function () {
  25444. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25445. return null;
  25446. },
  25447. enumerable: true,
  25448. configurable: true
  25449. });
  25450. /** @hidden */
  25451. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25452. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25453. return 0;
  25454. };
  25455. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25456. /** @hidden */
  25457. get: function () {
  25458. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25459. return null;
  25460. },
  25461. enumerable: true,
  25462. configurable: true
  25463. });
  25464. /**
  25465. * Gets the array of active meshes
  25466. * @returns an array of AbstractMesh
  25467. */
  25468. Scene.prototype.getActiveMeshes = function () {
  25469. return this._activeMeshes;
  25470. };
  25471. /** @hidden */
  25472. Scene.prototype.getRenderTargetsDuration = function () {
  25473. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25474. return 0;
  25475. };
  25476. /** @hidden */
  25477. Scene.prototype.getRenderDuration = function () {
  25478. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25479. return 0;
  25480. };
  25481. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25482. /** @hidden */
  25483. get: function () {
  25484. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25485. return null;
  25486. },
  25487. enumerable: true,
  25488. configurable: true
  25489. });
  25490. /** @hidden */
  25491. Scene.prototype.getParticlesDuration = function () {
  25492. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25493. return 0;
  25494. };
  25495. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25496. /** @hidden */
  25497. get: function () {
  25498. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25499. return null;
  25500. },
  25501. enumerable: true,
  25502. configurable: true
  25503. });
  25504. /** @hidden */
  25505. Scene.prototype.getSpritesDuration = function () {
  25506. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25507. return 0;
  25508. };
  25509. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25510. /** @hidden */
  25511. get: function () {
  25512. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25513. return null;
  25514. },
  25515. enumerable: true,
  25516. configurable: true
  25517. });
  25518. /**
  25519. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25520. * @returns a number
  25521. */
  25522. Scene.prototype.getAnimationRatio = function () {
  25523. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25524. };
  25525. /**
  25526. * Gets an unique Id for the current render phase
  25527. * @returns a number
  25528. */
  25529. Scene.prototype.getRenderId = function () {
  25530. return this._renderId;
  25531. };
  25532. /**
  25533. * Gets an unique Id for the current frame
  25534. * @returns a number
  25535. */
  25536. Scene.prototype.getFrameId = function () {
  25537. return this._frameId;
  25538. };
  25539. /** Call this function if you want to manually increment the render Id*/
  25540. Scene.prototype.incrementRenderId = function () {
  25541. this._renderId++;
  25542. };
  25543. Scene.prototype._updatePointerPosition = function (evt) {
  25544. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25545. if (!canvasRect) {
  25546. return;
  25547. }
  25548. this._pointerX = evt.clientX - canvasRect.left;
  25549. this._pointerY = evt.clientY - canvasRect.top;
  25550. this._unTranslatedPointerX = this._pointerX;
  25551. this._unTranslatedPointerY = this._pointerY;
  25552. };
  25553. Scene.prototype._createUbo = function () {
  25554. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25555. this._sceneUbo.addUniform("viewProjection", 16);
  25556. this._sceneUbo.addUniform("view", 16);
  25557. };
  25558. Scene.prototype._createAlternateUbo = function () {
  25559. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25560. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25561. this._alternateSceneUbo.addUniform("view", 16);
  25562. };
  25563. // Pointers handling
  25564. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25565. if (pointerInfo.pickInfo) {
  25566. if (!pointerInfo.pickInfo.ray) {
  25567. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25568. }
  25569. }
  25570. };
  25571. /**
  25572. * Use this method to simulate a pointer move on a mesh
  25573. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25574. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25575. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25576. * @returns the current scene
  25577. */
  25578. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25579. var evt = new PointerEvent("pointermove", pointerEventInit);
  25580. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25581. return this;
  25582. }
  25583. return this._processPointerMove(pickResult, evt);
  25584. };
  25585. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25586. var canvas = this._engine.getRenderingCanvas();
  25587. if (!canvas) {
  25588. return this;
  25589. }
  25590. // Restore pointer
  25591. canvas.style.cursor = this.defaultCursor;
  25592. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25593. if (isMeshPicked) {
  25594. this.setPointerOverMesh(pickResult.pickedMesh);
  25595. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25596. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25597. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25598. }
  25599. else {
  25600. canvas.style.cursor = this.hoverCursor;
  25601. }
  25602. }
  25603. }
  25604. else {
  25605. this.setPointerOverMesh(null);
  25606. }
  25607. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25608. var step = _a[_i];
  25609. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25610. }
  25611. if (pickResult) {
  25612. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25613. if (this.onPointerMove) {
  25614. this.onPointerMove(evt, pickResult, type);
  25615. }
  25616. if (this.onPointerObservable.hasObservers()) {
  25617. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25618. this._setRayOnPointerInfo(pi);
  25619. this.onPointerObservable.notifyObservers(pi, type);
  25620. }
  25621. }
  25622. return this;
  25623. };
  25624. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25625. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25626. if (pickResult) {
  25627. pi.ray = pickResult.ray;
  25628. }
  25629. this.onPrePointerObservable.notifyObservers(pi, type);
  25630. if (pi.skipOnPointerObservable) {
  25631. return true;
  25632. }
  25633. else {
  25634. return false;
  25635. }
  25636. };
  25637. /**
  25638. * Use this method to simulate a pointer down on a mesh
  25639. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25640. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25641. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25642. * @returns the current scene
  25643. */
  25644. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25645. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25646. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25647. return this;
  25648. }
  25649. return this._processPointerDown(pickResult, evt);
  25650. };
  25651. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25652. var _this = this;
  25653. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25654. this._pickedDownMesh = pickResult.pickedMesh;
  25655. var actionManager = pickResult.pickedMesh.actionManager;
  25656. if (actionManager) {
  25657. if (actionManager.hasPickTriggers) {
  25658. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25659. switch (evt.button) {
  25660. case 0:
  25661. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25662. break;
  25663. case 1:
  25664. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25665. break;
  25666. case 2:
  25667. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25668. break;
  25669. }
  25670. }
  25671. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25672. window.setTimeout(function () {
  25673. 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);
  25674. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25675. if (_this._totalPointersPressed !== 0 &&
  25676. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25677. !_this._isPointerSwiping()) {
  25678. _this._startingPointerTime = 0;
  25679. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25680. }
  25681. }
  25682. }, Scene.LongPressDelay);
  25683. }
  25684. }
  25685. }
  25686. else {
  25687. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25688. var step = _a[_i];
  25689. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25690. }
  25691. }
  25692. if (pickResult) {
  25693. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25694. if (this.onPointerDown) {
  25695. this.onPointerDown(evt, pickResult, type);
  25696. }
  25697. if (this.onPointerObservable.hasObservers()) {
  25698. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25699. this._setRayOnPointerInfo(pi);
  25700. this.onPointerObservable.notifyObservers(pi, type);
  25701. }
  25702. }
  25703. return this;
  25704. };
  25705. /**
  25706. * Use this method to simulate a pointer up on a mesh
  25707. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25708. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25709. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25710. * @returns the current scene
  25711. */
  25712. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25713. var evt = new PointerEvent("pointerup", pointerEventInit);
  25714. var clickInfo = new ClickInfo();
  25715. clickInfo.singleClick = true;
  25716. clickInfo.ignore = true;
  25717. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25718. return this;
  25719. }
  25720. return this._processPointerUp(pickResult, evt, clickInfo);
  25721. };
  25722. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25723. if (pickResult && pickResult && pickResult.pickedMesh) {
  25724. this._pickedUpMesh = pickResult.pickedMesh;
  25725. if (this._pickedDownMesh === this._pickedUpMesh) {
  25726. if (this.onPointerPick) {
  25727. this.onPointerPick(evt, pickResult);
  25728. }
  25729. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25730. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25731. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25732. this._setRayOnPointerInfo(pi);
  25733. this.onPointerObservable.notifyObservers(pi, type_1);
  25734. }
  25735. }
  25736. if (pickResult.pickedMesh.actionManager) {
  25737. if (clickInfo.ignore) {
  25738. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25739. }
  25740. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25741. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25742. }
  25743. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25744. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25745. }
  25746. }
  25747. }
  25748. else {
  25749. if (!clickInfo.ignore) {
  25750. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25751. var step = _a[_i];
  25752. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25753. }
  25754. }
  25755. }
  25756. if (this._pickedDownMesh &&
  25757. this._pickedDownMesh.actionManager &&
  25758. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25759. this._pickedDownMesh !== this._pickedUpMesh) {
  25760. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25761. }
  25762. var type = BABYLON.PointerEventTypes.POINTERUP;
  25763. if (this.onPointerObservable.hasObservers()) {
  25764. if (!clickInfo.ignore) {
  25765. if (!clickInfo.hasSwiped) {
  25766. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25767. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25768. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25769. this._setRayOnPointerInfo(pi);
  25770. this.onPointerObservable.notifyObservers(pi, type_2);
  25771. }
  25772. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25773. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25774. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25775. this._setRayOnPointerInfo(pi);
  25776. this.onPointerObservable.notifyObservers(pi, type_3);
  25777. }
  25778. }
  25779. }
  25780. else {
  25781. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25782. this._setRayOnPointerInfo(pi);
  25783. this.onPointerObservable.notifyObservers(pi, type);
  25784. }
  25785. }
  25786. if (this.onPointerUp) {
  25787. this.onPointerUp(evt, pickResult, type);
  25788. }
  25789. return this;
  25790. };
  25791. /**
  25792. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25793. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25794. * @returns true if the pointer was captured
  25795. */
  25796. Scene.prototype.isPointerCaptured = function (pointerId) {
  25797. if (pointerId === void 0) { pointerId = 0; }
  25798. return this._pointerCaptures[pointerId];
  25799. };
  25800. /** @hidden */
  25801. Scene.prototype._isPointerSwiping = function () {
  25802. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25803. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25804. };
  25805. /**
  25806. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25807. * @param attachUp defines if you want to attach events to pointerup
  25808. * @param attachDown defines if you want to attach events to pointerdown
  25809. * @param attachMove defines if you want to attach events to pointermove
  25810. */
  25811. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25812. var _this = this;
  25813. if (attachUp === void 0) { attachUp = true; }
  25814. if (attachDown === void 0) { attachDown = true; }
  25815. if (attachMove === void 0) { attachMove = true; }
  25816. this._initActionManager = function (act, clickInfo) {
  25817. if (!_this._meshPickProceed) {
  25818. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25819. _this._currentPickResult = pickResult;
  25820. if (pickResult) {
  25821. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25822. }
  25823. _this._meshPickProceed = true;
  25824. }
  25825. return act;
  25826. };
  25827. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25828. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25829. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25830. btn !== _this._previousButtonPressed) {
  25831. _this._doubleClickOccured = false;
  25832. clickInfo.singleClick = true;
  25833. clickInfo.ignore = false;
  25834. cb(clickInfo, _this._currentPickResult);
  25835. }
  25836. };
  25837. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25838. var clickInfo = new ClickInfo();
  25839. _this._currentPickResult = null;
  25840. var act = null;
  25841. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25842. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25843. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25844. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25845. act = _this._initActionManager(act, clickInfo);
  25846. if (act)
  25847. checkPicking = act.hasPickTriggers;
  25848. }
  25849. if (checkPicking) {
  25850. var btn = evt.button;
  25851. clickInfo.hasSwiped = _this._isPointerSwiping();
  25852. if (!clickInfo.hasSwiped) {
  25853. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25854. if (!checkSingleClickImmediately) {
  25855. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25856. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25857. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25858. act = _this._initActionManager(act, clickInfo);
  25859. if (act)
  25860. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25861. }
  25862. }
  25863. if (checkSingleClickImmediately) {
  25864. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25865. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25866. btn !== _this._previousButtonPressed) {
  25867. clickInfo.singleClick = true;
  25868. cb(clickInfo, _this._currentPickResult);
  25869. }
  25870. }
  25871. // at least one double click is required to be check and exclusive double click is enabled
  25872. else {
  25873. // wait that no double click has been raised during the double click delay
  25874. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25875. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25876. }
  25877. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25878. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25879. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25880. act = _this._initActionManager(act, clickInfo);
  25881. if (act)
  25882. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25883. }
  25884. if (checkDoubleClick) {
  25885. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25886. if (btn === _this._previousButtonPressed &&
  25887. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25888. !_this._doubleClickOccured) {
  25889. // pointer has not moved for 2 clicks, it's a double click
  25890. if (!clickInfo.hasSwiped &&
  25891. !_this._isPointerSwiping()) {
  25892. _this._previousStartingPointerTime = 0;
  25893. _this._doubleClickOccured = true;
  25894. clickInfo.doubleClick = true;
  25895. clickInfo.ignore = false;
  25896. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25897. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25898. }
  25899. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25900. cb(clickInfo, _this._currentPickResult);
  25901. }
  25902. // if the two successive clicks are too far, it's just two simple clicks
  25903. else {
  25904. _this._doubleClickOccured = false;
  25905. _this._previousStartingPointerTime = _this._startingPointerTime;
  25906. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25907. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25908. _this._previousButtonPressed = btn;
  25909. if (Scene.ExclusiveDoubleClickMode) {
  25910. if (_this._previousDelayedSimpleClickTimeout) {
  25911. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25912. }
  25913. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25914. cb(clickInfo, _this._previousPickResult);
  25915. }
  25916. else {
  25917. cb(clickInfo, _this._currentPickResult);
  25918. }
  25919. }
  25920. }
  25921. // just the first click of the double has been raised
  25922. else {
  25923. _this._doubleClickOccured = false;
  25924. _this._previousStartingPointerTime = _this._startingPointerTime;
  25925. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25926. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25927. _this._previousButtonPressed = btn;
  25928. }
  25929. }
  25930. }
  25931. }
  25932. clickInfo.ignore = true;
  25933. cb(clickInfo, _this._currentPickResult);
  25934. };
  25935. this._onPointerMove = function (evt) {
  25936. _this._updatePointerPosition(evt);
  25937. // PreObservable support
  25938. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25939. return;
  25940. }
  25941. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25942. return;
  25943. }
  25944. if (!_this.pointerMovePredicate) {
  25945. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25946. }
  25947. // Meshes
  25948. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25949. _this._processPointerMove(pickResult, evt);
  25950. };
  25951. this._onPointerDown = function (evt) {
  25952. _this._totalPointersPressed++;
  25953. _this._pickedDownMesh = null;
  25954. _this._meshPickProceed = false;
  25955. _this._updatePointerPosition(evt);
  25956. if (_this.preventDefaultOnPointerDown && canvas) {
  25957. evt.preventDefault();
  25958. canvas.focus();
  25959. }
  25960. // PreObservable support
  25961. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25962. return;
  25963. }
  25964. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25965. return;
  25966. }
  25967. _this._pointerCaptures[evt.pointerId] = true;
  25968. _this._startingPointerPosition.x = _this._pointerX;
  25969. _this._startingPointerPosition.y = _this._pointerY;
  25970. _this._startingPointerTime = Date.now();
  25971. if (!_this.pointerDownPredicate) {
  25972. _this.pointerDownPredicate = function (mesh) {
  25973. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25974. };
  25975. }
  25976. // Meshes
  25977. _this._pickedDownMesh = null;
  25978. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25979. _this._processPointerDown(pickResult, evt);
  25980. };
  25981. this._onPointerUp = function (evt) {
  25982. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25983. return; // So we need to test it the pointer down was pressed before.
  25984. }
  25985. _this._totalPointersPressed--;
  25986. _this._pickedUpMesh = null;
  25987. _this._meshPickProceed = false;
  25988. _this._updatePointerPosition(evt);
  25989. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25990. // PreObservable support
  25991. if (_this.onPrePointerObservable.hasObservers()) {
  25992. if (!clickInfo.ignore) {
  25993. if (!clickInfo.hasSwiped) {
  25994. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25995. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25996. return;
  25997. }
  25998. }
  25999. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26000. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26001. return;
  26002. }
  26003. }
  26004. }
  26005. }
  26006. else {
  26007. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26008. return;
  26009. }
  26010. }
  26011. }
  26012. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26013. return;
  26014. }
  26015. _this._pointerCaptures[evt.pointerId] = false;
  26016. if (!_this.pointerUpPredicate) {
  26017. _this.pointerUpPredicate = function (mesh) {
  26018. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26019. };
  26020. }
  26021. // Meshes
  26022. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26023. _this._initActionManager(null, clickInfo);
  26024. }
  26025. if (!pickResult) {
  26026. pickResult = _this._currentPickResult;
  26027. }
  26028. _this._processPointerUp(pickResult, evt, clickInfo);
  26029. _this._previousPickResult = _this._currentPickResult;
  26030. });
  26031. };
  26032. this._onKeyDown = function (evt) {
  26033. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26034. if (_this.onPreKeyboardObservable.hasObservers()) {
  26035. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26036. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26037. if (pi.skipOnPointerObservable) {
  26038. return;
  26039. }
  26040. }
  26041. if (_this.onKeyboardObservable.hasObservers()) {
  26042. var pi = new BABYLON.KeyboardInfo(type, evt);
  26043. _this.onKeyboardObservable.notifyObservers(pi, type);
  26044. }
  26045. if (_this.actionManager) {
  26046. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26047. }
  26048. };
  26049. this._onKeyUp = function (evt) {
  26050. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26051. if (_this.onPreKeyboardObservable.hasObservers()) {
  26052. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26053. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26054. if (pi.skipOnPointerObservable) {
  26055. return;
  26056. }
  26057. }
  26058. if (_this.onKeyboardObservable.hasObservers()) {
  26059. var pi = new BABYLON.KeyboardInfo(type, evt);
  26060. _this.onKeyboardObservable.notifyObservers(pi, type);
  26061. }
  26062. if (_this.actionManager) {
  26063. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26064. }
  26065. };
  26066. var engine = this.getEngine();
  26067. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26068. if (!canvas) {
  26069. return;
  26070. }
  26071. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26072. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26073. });
  26074. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26075. if (!canvas) {
  26076. return;
  26077. }
  26078. canvas.removeEventListener("keydown", _this._onKeyDown);
  26079. canvas.removeEventListener("keyup", _this._onKeyUp);
  26080. });
  26081. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26082. var canvas = this._engine.getRenderingCanvas();
  26083. if (!canvas) {
  26084. return;
  26085. }
  26086. if (attachMove) {
  26087. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26088. // Wheel
  26089. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26090. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26091. }
  26092. if (attachDown) {
  26093. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26094. }
  26095. if (attachUp) {
  26096. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26097. }
  26098. canvas.tabIndex = 1;
  26099. };
  26100. /** Detaches all event handlers*/
  26101. Scene.prototype.detachControl = function () {
  26102. var engine = this.getEngine();
  26103. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26104. var canvas = engine.getRenderingCanvas();
  26105. if (!canvas) {
  26106. return;
  26107. }
  26108. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26109. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26110. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26111. if (this._onCanvasBlurObserver) {
  26112. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26113. }
  26114. if (this._onCanvasFocusObserver) {
  26115. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26116. }
  26117. // Wheel
  26118. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26119. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26120. // Keyboard
  26121. canvas.removeEventListener("keydown", this._onKeyDown);
  26122. canvas.removeEventListener("keyup", this._onKeyUp);
  26123. // Observables
  26124. this.onKeyboardObservable.clear();
  26125. this.onPreKeyboardObservable.clear();
  26126. this.onPointerObservable.clear();
  26127. this.onPrePointerObservable.clear();
  26128. };
  26129. /**
  26130. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26131. * Delay loaded resources are not taking in account
  26132. * @return true if all required resources are ready
  26133. */
  26134. Scene.prototype.isReady = function () {
  26135. if (this._isDisposed) {
  26136. return false;
  26137. }
  26138. if (this._pendingData.length > 0) {
  26139. return false;
  26140. }
  26141. var index;
  26142. var engine = this.getEngine();
  26143. // Geometries
  26144. for (index = 0; index < this.geometries.length; index++) {
  26145. var geometry = this.geometries[index];
  26146. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26147. return false;
  26148. }
  26149. }
  26150. // Meshes
  26151. for (index = 0; index < this.meshes.length; index++) {
  26152. var mesh = this.meshes[index];
  26153. if (!mesh.isEnabled()) {
  26154. continue;
  26155. }
  26156. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26157. continue;
  26158. }
  26159. if (!mesh.isReady(true)) {
  26160. return false;
  26161. }
  26162. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26163. // Is Ready For Mesh
  26164. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26165. var step = _a[_i];
  26166. if (!step.action(mesh, hardwareInstancedRendering)) {
  26167. return false;
  26168. }
  26169. }
  26170. }
  26171. // Post-processes
  26172. if (this.activeCameras && this.activeCameras.length > 0) {
  26173. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26174. var camera = _c[_b];
  26175. if (!camera.isReady(true)) {
  26176. return false;
  26177. }
  26178. }
  26179. }
  26180. else if (this.activeCamera) {
  26181. if (!this.activeCamera.isReady(true)) {
  26182. return false;
  26183. }
  26184. }
  26185. // Particles
  26186. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26187. var particleSystem = _e[_d];
  26188. if (!particleSystem.isReady()) {
  26189. return false;
  26190. }
  26191. }
  26192. return true;
  26193. };
  26194. /** Resets all cached information relative to material (including effect and visibility) */
  26195. Scene.prototype.resetCachedMaterial = function () {
  26196. this._cachedMaterial = null;
  26197. this._cachedEffect = null;
  26198. this._cachedVisibility = null;
  26199. };
  26200. /**
  26201. * Registers a function to be called before every frame render
  26202. * @param func defines the function to register
  26203. */
  26204. Scene.prototype.registerBeforeRender = function (func) {
  26205. this.onBeforeRenderObservable.add(func);
  26206. };
  26207. /**
  26208. * Unregisters a function called before every frame render
  26209. * @param func defines the function to unregister
  26210. */
  26211. Scene.prototype.unregisterBeforeRender = function (func) {
  26212. this.onBeforeRenderObservable.removeCallback(func);
  26213. };
  26214. /**
  26215. * Registers a function to be called after every frame render
  26216. * @param func defines the function to register
  26217. */
  26218. Scene.prototype.registerAfterRender = function (func) {
  26219. this.onAfterRenderObservable.add(func);
  26220. };
  26221. /**
  26222. * Unregisters a function called after every frame render
  26223. * @param func defines the function to unregister
  26224. */
  26225. Scene.prototype.unregisterAfterRender = function (func) {
  26226. this.onAfterRenderObservable.removeCallback(func);
  26227. };
  26228. Scene.prototype._executeOnceBeforeRender = function (func) {
  26229. var _this = this;
  26230. var execFunc = function () {
  26231. func();
  26232. setTimeout(function () {
  26233. _this.unregisterBeforeRender(execFunc);
  26234. });
  26235. };
  26236. this.registerBeforeRender(execFunc);
  26237. };
  26238. /**
  26239. * The provided function will run before render once and will be disposed afterwards.
  26240. * A timeout delay can be provided so that the function will be executed in N ms.
  26241. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26242. * @param func The function to be executed.
  26243. * @param timeout optional delay in ms
  26244. */
  26245. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26246. var _this = this;
  26247. if (timeout !== undefined) {
  26248. setTimeout(function () {
  26249. _this._executeOnceBeforeRender(func);
  26250. }, timeout);
  26251. }
  26252. else {
  26253. this._executeOnceBeforeRender(func);
  26254. }
  26255. };
  26256. /** @hidden */
  26257. Scene.prototype._addPendingData = function (data) {
  26258. this._pendingData.push(data);
  26259. };
  26260. /** @hidden */
  26261. Scene.prototype._removePendingData = function (data) {
  26262. var wasLoading = this.isLoading;
  26263. var index = this._pendingData.indexOf(data);
  26264. if (index !== -1) {
  26265. this._pendingData.splice(index, 1);
  26266. }
  26267. if (wasLoading && !this.isLoading) {
  26268. this.onDataLoadedObservable.notifyObservers(this);
  26269. }
  26270. };
  26271. /**
  26272. * Returns the number of items waiting to be loaded
  26273. * @returns the number of items waiting to be loaded
  26274. */
  26275. Scene.prototype.getWaitingItemsCount = function () {
  26276. return this._pendingData.length;
  26277. };
  26278. Object.defineProperty(Scene.prototype, "isLoading", {
  26279. /**
  26280. * Returns a boolean indicating if the scene is still loading data
  26281. */
  26282. get: function () {
  26283. return this._pendingData.length > 0;
  26284. },
  26285. enumerable: true,
  26286. configurable: true
  26287. });
  26288. /**
  26289. * Registers a function to be executed when the scene is ready
  26290. * @param {Function} func - the function to be executed
  26291. */
  26292. Scene.prototype.executeWhenReady = function (func) {
  26293. var _this = this;
  26294. this.onReadyObservable.add(func);
  26295. if (this._executeWhenReadyTimeoutId !== -1) {
  26296. return;
  26297. }
  26298. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26299. _this._checkIsReady();
  26300. }, 150);
  26301. };
  26302. /**
  26303. * Returns a promise that resolves when the scene is ready
  26304. * @returns A promise that resolves when the scene is ready
  26305. */
  26306. Scene.prototype.whenReadyAsync = function () {
  26307. var _this = this;
  26308. return new Promise(function (resolve) {
  26309. _this.executeWhenReady(function () {
  26310. resolve();
  26311. });
  26312. });
  26313. };
  26314. /** @hidden */
  26315. Scene.prototype._checkIsReady = function () {
  26316. var _this = this;
  26317. this._registerTransientComponents();
  26318. if (this.isReady()) {
  26319. this.onReadyObservable.notifyObservers(this);
  26320. this.onReadyObservable.clear();
  26321. this._executeWhenReadyTimeoutId = -1;
  26322. return;
  26323. }
  26324. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26325. _this._checkIsReady();
  26326. }, 150);
  26327. };
  26328. // Animations
  26329. /**
  26330. * Will start the animation sequence of a given target
  26331. * @param target defines the target
  26332. * @param from defines from which frame should animation start
  26333. * @param to defines until which frame should animation run.
  26334. * @param weight defines the weight to apply to the animation (1.0 by default)
  26335. * @param loop defines if the animation loops
  26336. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26337. * @param onAnimationEnd defines the function to be executed when the animation ends
  26338. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26339. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26340. * @returns the animatable object created for this animation
  26341. */
  26342. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26343. if (weight === void 0) { weight = 1.0; }
  26344. if (speedRatio === void 0) { speedRatio = 1.0; }
  26345. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26346. returnedAnimatable.weight = weight;
  26347. return returnedAnimatable;
  26348. };
  26349. /**
  26350. * Will start the animation sequence of a given target
  26351. * @param target defines the target
  26352. * @param from defines from which frame should animation start
  26353. * @param to defines until which frame should animation run.
  26354. * @param loop defines if the animation loops
  26355. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26356. * @param onAnimationEnd defines the function to be executed when the animation ends
  26357. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26358. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26359. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26360. * @returns the animatable object created for this animation
  26361. */
  26362. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26363. if (speedRatio === void 0) { speedRatio = 1.0; }
  26364. if (stopCurrent === void 0) { stopCurrent = true; }
  26365. if (from > to && speedRatio > 0) {
  26366. speedRatio *= -1;
  26367. }
  26368. if (stopCurrent) {
  26369. this.stopAnimation(target, undefined, targetMask);
  26370. }
  26371. if (!animatable) {
  26372. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26373. }
  26374. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26375. // Local animations
  26376. if (target.animations && shouldRunTargetAnimations) {
  26377. animatable.appendAnimations(target, target.animations);
  26378. }
  26379. // Children animations
  26380. if (target.getAnimatables) {
  26381. var animatables = target.getAnimatables();
  26382. for (var index = 0; index < animatables.length; index++) {
  26383. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26384. }
  26385. }
  26386. animatable.reset();
  26387. return animatable;
  26388. };
  26389. /**
  26390. * Begin a new animation on a given node
  26391. * @param target defines the target where the animation will take place
  26392. * @param animations defines the list of animations to start
  26393. * @param from defines the initial value
  26394. * @param to defines the final value
  26395. * @param loop defines if you want animation to loop (off by default)
  26396. * @param speedRatio defines the speed ratio to apply to all animations
  26397. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26398. * @returns the list of created animatables
  26399. */
  26400. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26401. if (speedRatio === undefined) {
  26402. speedRatio = 1.0;
  26403. }
  26404. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26405. return animatable;
  26406. };
  26407. /**
  26408. * Begin a new animation on a given node and its hierarchy
  26409. * @param target defines the root node where the animation will take place
  26410. * @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.
  26411. * @param animations defines the list of animations to start
  26412. * @param from defines the initial value
  26413. * @param to defines the final value
  26414. * @param loop defines if you want animation to loop (off by default)
  26415. * @param speedRatio defines the speed ratio to apply to all animations
  26416. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26417. * @returns the list of animatables created for all nodes
  26418. */
  26419. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26420. var children = target.getDescendants(directDescendantsOnly);
  26421. var result = [];
  26422. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26423. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26424. var child = children_1[_i];
  26425. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26426. }
  26427. return result;
  26428. };
  26429. /**
  26430. * Gets the animatable associated with a specific target
  26431. * @param target defines the target of the animatable
  26432. * @returns the required animatable if found
  26433. */
  26434. Scene.prototype.getAnimatableByTarget = function (target) {
  26435. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26436. if (this._activeAnimatables[index].target === target) {
  26437. return this._activeAnimatables[index];
  26438. }
  26439. }
  26440. return null;
  26441. };
  26442. /**
  26443. * Gets all animatables associated with a given target
  26444. * @param target defines the target to look animatables for
  26445. * @returns an array of Animatables
  26446. */
  26447. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26448. var result = [];
  26449. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26450. if (this._activeAnimatables[index].target === target) {
  26451. result.push(this._activeAnimatables[index]);
  26452. }
  26453. }
  26454. return result;
  26455. };
  26456. Object.defineProperty(Scene.prototype, "animatables", {
  26457. /**
  26458. * Gets all animatable attached to the scene
  26459. */
  26460. get: function () {
  26461. return this._activeAnimatables;
  26462. },
  26463. enumerable: true,
  26464. configurable: true
  26465. });
  26466. /**
  26467. * Will stop the animation of the given target
  26468. * @param target - the target
  26469. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26470. * @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)
  26471. */
  26472. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26473. var animatables = this.getAllAnimatablesByTarget(target);
  26474. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26475. var animatable = animatables_1[_i];
  26476. animatable.stop(animationName, targetMask);
  26477. }
  26478. };
  26479. /**
  26480. * Stops and removes all animations that have been applied to the scene
  26481. */
  26482. Scene.prototype.stopAllAnimations = function () {
  26483. if (this._activeAnimatables) {
  26484. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26485. this._activeAnimatables[i].stop();
  26486. }
  26487. this._activeAnimatables = [];
  26488. }
  26489. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26490. var group = _a[_i];
  26491. group.stop();
  26492. }
  26493. };
  26494. Scene.prototype._animate = function () {
  26495. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26496. return;
  26497. }
  26498. // Getting time
  26499. var now = BABYLON.Tools.Now;
  26500. if (!this._animationTimeLast) {
  26501. if (this._pendingData.length > 0) {
  26502. return;
  26503. }
  26504. this._animationTimeLast = now;
  26505. }
  26506. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26507. this._animationTime += deltaTime;
  26508. this._animationTimeLast = now;
  26509. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26510. this._activeAnimatables[index]._animate(this._animationTime);
  26511. }
  26512. // Late animation bindings
  26513. this._processLateAnimationBindings();
  26514. };
  26515. /** @hidden */
  26516. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26517. var target = runtimeAnimation.target;
  26518. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26519. if (!target._lateAnimationHolders) {
  26520. target._lateAnimationHolders = {};
  26521. }
  26522. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26523. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26524. totalWeight: 0,
  26525. animations: [],
  26526. originalValue: originalValue
  26527. };
  26528. }
  26529. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26530. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26531. };
  26532. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26533. var normalizer = 1.0;
  26534. var finalPosition = BABYLON.Tmp.Vector3[0];
  26535. var finalScaling = BABYLON.Tmp.Vector3[1];
  26536. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26537. var startIndex = 0;
  26538. var originalAnimation = holder.animations[0];
  26539. var originalValue = holder.originalValue;
  26540. var scale = 1;
  26541. if (holder.totalWeight < 1.0) {
  26542. // We need to mix the original value in
  26543. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26544. scale = 1.0 - holder.totalWeight;
  26545. }
  26546. else {
  26547. startIndex = 1;
  26548. // We need to normalize the weights
  26549. normalizer = holder.totalWeight;
  26550. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26551. scale = originalAnimation.weight / normalizer;
  26552. if (scale == 1) {
  26553. return originalAnimation.currentValue;
  26554. }
  26555. }
  26556. finalScaling.scaleInPlace(scale);
  26557. finalPosition.scaleInPlace(scale);
  26558. finalQuaternion.scaleInPlace(scale);
  26559. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26560. var runtimeAnimation = holder.animations[animIndex];
  26561. var scale = runtimeAnimation.weight / normalizer;
  26562. var currentPosition = BABYLON.Tmp.Vector3[2];
  26563. var currentScaling = BABYLON.Tmp.Vector3[3];
  26564. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26565. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26566. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26567. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26568. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26569. }
  26570. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26571. return originalAnimation._workValue;
  26572. };
  26573. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26574. var originalAnimation = holder.animations[0];
  26575. var originalValue = holder.originalValue;
  26576. if (holder.animations.length === 1) {
  26577. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26578. return refQuaternion;
  26579. }
  26580. var normalizer = 1.0;
  26581. var quaternions;
  26582. var weights;
  26583. if (holder.totalWeight < 1.0) {
  26584. var scale = 1.0 - holder.totalWeight;
  26585. quaternions = [];
  26586. weights = [];
  26587. quaternions.push(originalValue);
  26588. weights.push(scale);
  26589. }
  26590. else {
  26591. if (holder.animations.length === 2) { // Slerp as soon as we can
  26592. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26593. return refQuaternion;
  26594. }
  26595. quaternions = [];
  26596. weights = [];
  26597. normalizer = holder.totalWeight;
  26598. }
  26599. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26600. var runtimeAnimation = holder.animations[animIndex];
  26601. quaternions.push(runtimeAnimation.currentValue);
  26602. weights.push(runtimeAnimation.weight / normalizer);
  26603. }
  26604. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26605. var cumulativeAmount = 0;
  26606. var cumulativeQuaternion = null;
  26607. for (var index = 0; index < quaternions.length;) {
  26608. if (!cumulativeQuaternion) {
  26609. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26610. cumulativeQuaternion = refQuaternion;
  26611. cumulativeAmount = weights[index] + weights[index + 1];
  26612. index += 2;
  26613. continue;
  26614. }
  26615. cumulativeAmount += weights[index];
  26616. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26617. index++;
  26618. }
  26619. return cumulativeQuaternion;
  26620. };
  26621. Scene.prototype._processLateAnimationBindings = function () {
  26622. if (!this._registeredForLateAnimationBindings.length) {
  26623. return;
  26624. }
  26625. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26626. var target = this._registeredForLateAnimationBindings.data[index];
  26627. for (var path in target._lateAnimationHolders) {
  26628. var holder = target._lateAnimationHolders[path];
  26629. var originalAnimation = holder.animations[0];
  26630. var originalValue = holder.originalValue;
  26631. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26632. var finalValue = target[path];
  26633. if (matrixDecomposeMode) {
  26634. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26635. }
  26636. else {
  26637. var quaternionMode = originalValue.w !== undefined;
  26638. if (quaternionMode) {
  26639. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26640. }
  26641. else {
  26642. var startIndex = 0;
  26643. var normalizer = 1.0;
  26644. if (holder.totalWeight < 1.0) {
  26645. // We need to mix the original value in
  26646. if (originalValue.scale) {
  26647. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26648. }
  26649. else {
  26650. finalValue = originalValue * (1.0 - holder.totalWeight);
  26651. }
  26652. }
  26653. else {
  26654. // We need to normalize the weights
  26655. normalizer = holder.totalWeight;
  26656. var scale_1 = originalAnimation.weight / normalizer;
  26657. if (scale_1 !== 1) {
  26658. if (originalAnimation.currentValue.scale) {
  26659. finalValue = originalAnimation.currentValue.scale(scale_1);
  26660. }
  26661. else {
  26662. finalValue = originalAnimation.currentValue * scale_1;
  26663. }
  26664. }
  26665. else {
  26666. finalValue = originalAnimation.currentValue;
  26667. }
  26668. startIndex = 1;
  26669. }
  26670. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26671. var runtimeAnimation = holder.animations[animIndex];
  26672. var scale = runtimeAnimation.weight / normalizer;
  26673. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26674. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26675. }
  26676. else {
  26677. finalValue += runtimeAnimation.currentValue * scale;
  26678. }
  26679. }
  26680. }
  26681. }
  26682. target[path] = finalValue;
  26683. }
  26684. target._lateAnimationHolders = {};
  26685. }
  26686. this._registeredForLateAnimationBindings.reset();
  26687. };
  26688. // Matrix
  26689. /** @hidden */
  26690. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26691. this._useAlternateCameraConfiguration = active;
  26692. };
  26693. /**
  26694. * Gets the current view matrix
  26695. * @returns a Matrix
  26696. */
  26697. Scene.prototype.getViewMatrix = function () {
  26698. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26699. };
  26700. /**
  26701. * Gets the current projection matrix
  26702. * @returns a Matrix
  26703. */
  26704. Scene.prototype.getProjectionMatrix = function () {
  26705. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26706. };
  26707. /**
  26708. * Gets the current transform matrix
  26709. * @returns a Matrix made of View * Projection
  26710. */
  26711. Scene.prototype.getTransformMatrix = function () {
  26712. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26713. };
  26714. /**
  26715. * Sets the current transform matrix
  26716. * @param view defines the View matrix to use
  26717. * @param projection defines the Projection matrix to use
  26718. */
  26719. Scene.prototype.setTransformMatrix = function (view, projection) {
  26720. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26721. return;
  26722. }
  26723. this._viewUpdateFlag = view.updateFlag;
  26724. this._projectionUpdateFlag = projection.updateFlag;
  26725. this._viewMatrix = view;
  26726. this._projectionMatrix = projection;
  26727. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26728. // Update frustum
  26729. if (!this._frustumPlanes) {
  26730. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26731. }
  26732. else {
  26733. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26734. }
  26735. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26736. var otherCamera = this.activeCamera._alternateCamera;
  26737. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26738. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26739. }
  26740. if (this._sceneUbo.useUbo) {
  26741. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26742. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26743. this._sceneUbo.update();
  26744. }
  26745. };
  26746. /** @hidden */
  26747. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26748. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26749. return;
  26750. }
  26751. this._alternateViewUpdateFlag = view.updateFlag;
  26752. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26753. this._alternateViewMatrix = view;
  26754. this._alternateProjectionMatrix = projection;
  26755. if (!this._alternateTransformMatrix) {
  26756. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26757. }
  26758. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26759. if (!this._alternateSceneUbo) {
  26760. this._createAlternateUbo();
  26761. }
  26762. if (this._alternateSceneUbo.useUbo) {
  26763. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26764. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26765. this._alternateSceneUbo.update();
  26766. }
  26767. };
  26768. /**
  26769. * Gets the uniform buffer used to store scene data
  26770. * @returns a UniformBuffer
  26771. */
  26772. Scene.prototype.getSceneUniformBuffer = function () {
  26773. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26774. };
  26775. /**
  26776. * Gets an unique (relatively to the current scene) Id
  26777. * @returns an unique number for the scene
  26778. */
  26779. Scene.prototype.getUniqueId = function () {
  26780. var result = Scene._uniqueIdCounter;
  26781. Scene._uniqueIdCounter++;
  26782. return result;
  26783. };
  26784. /**
  26785. * Add a mesh to the list of scene's meshes
  26786. * @param newMesh defines the mesh to add
  26787. * @param recursive if all child meshes should also be added to the scene
  26788. */
  26789. Scene.prototype.addMesh = function (newMesh, recursive) {
  26790. var _this = this;
  26791. if (recursive === void 0) { recursive = false; }
  26792. this.meshes.push(newMesh);
  26793. //notify the collision coordinator
  26794. if (this.collisionCoordinator) {
  26795. this.collisionCoordinator.onMeshAdded(newMesh);
  26796. }
  26797. newMesh._resyncLightSources();
  26798. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26799. if (recursive) {
  26800. newMesh.getChildMeshes().forEach(function (m) {
  26801. _this.addMesh(m);
  26802. });
  26803. }
  26804. };
  26805. /**
  26806. * Remove a mesh for the list of scene's meshes
  26807. * @param toRemove defines the mesh to remove
  26808. * @param recursive if all child meshes should also be removed from the scene
  26809. * @returns the index where the mesh was in the mesh list
  26810. */
  26811. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26812. var _this = this;
  26813. if (recursive === void 0) { recursive = false; }
  26814. var index = this.meshes.indexOf(toRemove);
  26815. if (index !== -1) {
  26816. // Remove from the scene if mesh found
  26817. this.meshes.splice(index, 1);
  26818. }
  26819. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26820. if (recursive) {
  26821. toRemove.getChildMeshes().forEach(function (m) {
  26822. _this.removeMesh(m);
  26823. });
  26824. }
  26825. return index;
  26826. };
  26827. /**
  26828. * Add a transform node to the list of scene's transform nodes
  26829. * @param newTransformNode defines the transform node to add
  26830. */
  26831. Scene.prototype.addTransformNode = function (newTransformNode) {
  26832. this.transformNodes.push(newTransformNode);
  26833. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26834. };
  26835. /**
  26836. * Remove a transform node for the list of scene's transform nodes
  26837. * @param toRemove defines the transform node to remove
  26838. * @returns the index where the transform node was in the transform node list
  26839. */
  26840. Scene.prototype.removeTransformNode = function (toRemove) {
  26841. var index = this.transformNodes.indexOf(toRemove);
  26842. if (index !== -1) {
  26843. // Remove from the scene if found
  26844. this.transformNodes.splice(index, 1);
  26845. }
  26846. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26847. return index;
  26848. };
  26849. /**
  26850. * Remove a skeleton for the list of scene's skeletons
  26851. * @param toRemove defines the skeleton to remove
  26852. * @returns the index where the skeleton was in the skeleton list
  26853. */
  26854. Scene.prototype.removeSkeleton = function (toRemove) {
  26855. var index = this.skeletons.indexOf(toRemove);
  26856. if (index !== -1) {
  26857. // Remove from the scene if found
  26858. this.skeletons.splice(index, 1);
  26859. }
  26860. return index;
  26861. };
  26862. /**
  26863. * Remove a morph target for the list of scene's morph targets
  26864. * @param toRemove defines the morph target to remove
  26865. * @returns the index where the morph target was in the morph target list
  26866. */
  26867. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26868. var index = this.morphTargetManagers.indexOf(toRemove);
  26869. if (index !== -1) {
  26870. // Remove from the scene if found
  26871. this.morphTargetManagers.splice(index, 1);
  26872. }
  26873. return index;
  26874. };
  26875. /**
  26876. * Remove a light for the list of scene's lights
  26877. * @param toRemove defines the light to remove
  26878. * @returns the index where the light was in the light list
  26879. */
  26880. Scene.prototype.removeLight = function (toRemove) {
  26881. var index = this.lights.indexOf(toRemove);
  26882. if (index !== -1) {
  26883. // Remove from meshes
  26884. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26885. var mesh = _a[_i];
  26886. mesh._removeLightSource(toRemove);
  26887. }
  26888. // Remove from the scene if mesh found
  26889. this.lights.splice(index, 1);
  26890. this.sortLightsByPriority();
  26891. }
  26892. this.onLightRemovedObservable.notifyObservers(toRemove);
  26893. return index;
  26894. };
  26895. /**
  26896. * Remove a camera for the list of scene's cameras
  26897. * @param toRemove defines the camera to remove
  26898. * @returns the index where the camera was in the camera list
  26899. */
  26900. Scene.prototype.removeCamera = function (toRemove) {
  26901. var index = this.cameras.indexOf(toRemove);
  26902. if (index !== -1) {
  26903. // Remove from the scene if mesh found
  26904. this.cameras.splice(index, 1);
  26905. }
  26906. // Remove from activeCameras
  26907. var index2 = this.activeCameras.indexOf(toRemove);
  26908. if (index2 !== -1) {
  26909. // Remove from the scene if mesh found
  26910. this.activeCameras.splice(index2, 1);
  26911. }
  26912. // Reset the activeCamera
  26913. if (this.activeCamera === toRemove) {
  26914. if (this.cameras.length > 0) {
  26915. this.activeCamera = this.cameras[0];
  26916. }
  26917. else {
  26918. this.activeCamera = null;
  26919. }
  26920. }
  26921. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26922. return index;
  26923. };
  26924. /**
  26925. * Remove a particle system for the list of scene's particle systems
  26926. * @param toRemove defines the particle system to remove
  26927. * @returns the index where the particle system was in the particle system list
  26928. */
  26929. Scene.prototype.removeParticleSystem = function (toRemove) {
  26930. var index = this.particleSystems.indexOf(toRemove);
  26931. if (index !== -1) {
  26932. this.particleSystems.splice(index, 1);
  26933. }
  26934. return index;
  26935. };
  26936. /**
  26937. * Remove a animation for the list of scene's animations
  26938. * @param toRemove defines the animation to remove
  26939. * @returns the index where the animation was in the animation list
  26940. */
  26941. Scene.prototype.removeAnimation = function (toRemove) {
  26942. var index = this.animations.indexOf(toRemove);
  26943. if (index !== -1) {
  26944. this.animations.splice(index, 1);
  26945. }
  26946. return index;
  26947. };
  26948. /**
  26949. * Removes the given animation group from this scene.
  26950. * @param toRemove The animation group to remove
  26951. * @returns The index of the removed animation group
  26952. */
  26953. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26954. var index = this.animationGroups.indexOf(toRemove);
  26955. if (index !== -1) {
  26956. this.animationGroups.splice(index, 1);
  26957. }
  26958. return index;
  26959. };
  26960. /**
  26961. * Removes the given multi-material from this scene.
  26962. * @param toRemove The multi-material to remove
  26963. * @returns The index of the removed multi-material
  26964. */
  26965. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26966. var index = this.multiMaterials.indexOf(toRemove);
  26967. if (index !== -1) {
  26968. this.multiMaterials.splice(index, 1);
  26969. }
  26970. return index;
  26971. };
  26972. /**
  26973. * Removes the given material from this scene.
  26974. * @param toRemove The material to remove
  26975. * @returns The index of the removed material
  26976. */
  26977. Scene.prototype.removeMaterial = function (toRemove) {
  26978. var index = this.materials.indexOf(toRemove);
  26979. if (index !== -1) {
  26980. this.materials.splice(index, 1);
  26981. }
  26982. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  26983. return index;
  26984. };
  26985. /**
  26986. * Removes the given action manager from this scene.
  26987. * @param toRemove The action manager to remove
  26988. * @returns The index of the removed action manager
  26989. */
  26990. Scene.prototype.removeActionManager = function (toRemove) {
  26991. var index = this.actionManagers.indexOf(toRemove);
  26992. if (index !== -1) {
  26993. this.actionManagers.splice(index, 1);
  26994. }
  26995. return index;
  26996. };
  26997. /**
  26998. * Removes the given texture from this scene.
  26999. * @param toRemove The texture to remove
  27000. * @returns The index of the removed texture
  27001. */
  27002. Scene.prototype.removeTexture = function (toRemove) {
  27003. var index = this.textures.indexOf(toRemove);
  27004. if (index !== -1) {
  27005. this.textures.splice(index, 1);
  27006. }
  27007. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27008. return index;
  27009. };
  27010. /**
  27011. * Adds the given light to this scene
  27012. * @param newLight The light to add
  27013. */
  27014. Scene.prototype.addLight = function (newLight) {
  27015. this.lights.push(newLight);
  27016. this.sortLightsByPriority();
  27017. // Add light to all meshes (To support if the light is removed and then readded)
  27018. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27019. var mesh = _a[_i];
  27020. if (mesh._lightSources.indexOf(newLight) === -1) {
  27021. mesh._lightSources.push(newLight);
  27022. mesh._resyncLightSources();
  27023. }
  27024. }
  27025. this.onNewLightAddedObservable.notifyObservers(newLight);
  27026. };
  27027. /**
  27028. * Sorts the list list based on light priorities
  27029. */
  27030. Scene.prototype.sortLightsByPriority = function () {
  27031. if (this.requireLightSorting) {
  27032. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27033. }
  27034. };
  27035. /**
  27036. * Adds the given camera to this scene
  27037. * @param newCamera The camera to add
  27038. */
  27039. Scene.prototype.addCamera = function (newCamera) {
  27040. this.cameras.push(newCamera);
  27041. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27042. };
  27043. /**
  27044. * Adds the given skeleton to this scene
  27045. * @param newSkeleton The skeleton to add
  27046. */
  27047. Scene.prototype.addSkeleton = function (newSkeleton) {
  27048. this.skeletons.push(newSkeleton);
  27049. };
  27050. /**
  27051. * Adds the given particle system to this scene
  27052. * @param newParticleSystem The particle system to add
  27053. */
  27054. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27055. this.particleSystems.push(newParticleSystem);
  27056. };
  27057. /**
  27058. * Adds the given animation to this scene
  27059. * @param newAnimation The animation to add
  27060. */
  27061. Scene.prototype.addAnimation = function (newAnimation) {
  27062. this.animations.push(newAnimation);
  27063. };
  27064. /**
  27065. * Adds the given animation group to this scene.
  27066. * @param newAnimationGroup The animation group to add
  27067. */
  27068. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27069. this.animationGroups.push(newAnimationGroup);
  27070. };
  27071. /**
  27072. * Adds the given multi-material to this scene
  27073. * @param newMultiMaterial The multi-material to add
  27074. */
  27075. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27076. this.multiMaterials.push(newMultiMaterial);
  27077. };
  27078. /**
  27079. * Adds the given material to this scene
  27080. * @param newMaterial The material to add
  27081. */
  27082. Scene.prototype.addMaterial = function (newMaterial) {
  27083. this.materials.push(newMaterial);
  27084. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27085. };
  27086. /**
  27087. * Adds the given morph target to this scene
  27088. * @param newMorphTargetManager The morph target to add
  27089. */
  27090. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27091. this.morphTargetManagers.push(newMorphTargetManager);
  27092. };
  27093. /**
  27094. * Adds the given geometry to this scene
  27095. * @param newGeometry The geometry to add
  27096. */
  27097. Scene.prototype.addGeometry = function (newGeometry) {
  27098. this.geometries.push(newGeometry);
  27099. };
  27100. /**
  27101. * Adds the given action manager to this scene
  27102. * @param newActionManager The action manager to add
  27103. */
  27104. Scene.prototype.addActionManager = function (newActionManager) {
  27105. this.actionManagers.push(newActionManager);
  27106. };
  27107. /**
  27108. * Adds the given texture to this scene.
  27109. * @param newTexture The texture to add
  27110. */
  27111. Scene.prototype.addTexture = function (newTexture) {
  27112. this.textures.push(newTexture);
  27113. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27114. };
  27115. /**
  27116. * Switch active camera
  27117. * @param newCamera defines the new active camera
  27118. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27119. */
  27120. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27121. if (attachControl === void 0) { attachControl = true; }
  27122. var canvas = this._engine.getRenderingCanvas();
  27123. if (!canvas) {
  27124. return;
  27125. }
  27126. if (this.activeCamera) {
  27127. this.activeCamera.detachControl(canvas);
  27128. }
  27129. this.activeCamera = newCamera;
  27130. if (attachControl) {
  27131. newCamera.attachControl(canvas);
  27132. }
  27133. };
  27134. /**
  27135. * sets the active camera of the scene using its ID
  27136. * @param id defines the camera's ID
  27137. * @return the new active camera or null if none found.
  27138. */
  27139. Scene.prototype.setActiveCameraByID = function (id) {
  27140. var camera = this.getCameraByID(id);
  27141. if (camera) {
  27142. this.activeCamera = camera;
  27143. return camera;
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * sets the active camera of the scene using its name
  27149. * @param name defines the camera's name
  27150. * @returns the new active camera or null if none found.
  27151. */
  27152. Scene.prototype.setActiveCameraByName = function (name) {
  27153. var camera = this.getCameraByName(name);
  27154. if (camera) {
  27155. this.activeCamera = camera;
  27156. return camera;
  27157. }
  27158. return null;
  27159. };
  27160. /**
  27161. * get an animation group using its name
  27162. * @param name defines the material's name
  27163. * @return the animation group or null if none found.
  27164. */
  27165. Scene.prototype.getAnimationGroupByName = function (name) {
  27166. for (var index = 0; index < this.animationGroups.length; index++) {
  27167. if (this.animationGroups[index].name === name) {
  27168. return this.animationGroups[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * get a material using its id
  27175. * @param id defines the material's ID
  27176. * @return the material or null if none found.
  27177. */
  27178. Scene.prototype.getMaterialByID = function (id) {
  27179. for (var index = 0; index < this.materials.length; index++) {
  27180. if (this.materials[index].id === id) {
  27181. return this.materials[index];
  27182. }
  27183. }
  27184. return null;
  27185. };
  27186. /**
  27187. * Gets a material using its name
  27188. * @param name defines the material's name
  27189. * @return the material or null if none found.
  27190. */
  27191. Scene.prototype.getMaterialByName = function (name) {
  27192. for (var index = 0; index < this.materials.length; index++) {
  27193. if (this.materials[index].name === name) {
  27194. return this.materials[index];
  27195. }
  27196. }
  27197. return null;
  27198. };
  27199. /**
  27200. * Gets a camera using its id
  27201. * @param id defines the id to look for
  27202. * @returns the camera or null if not found
  27203. */
  27204. Scene.prototype.getCameraByID = function (id) {
  27205. for (var index = 0; index < this.cameras.length; index++) {
  27206. if (this.cameras[index].id === id) {
  27207. return this.cameras[index];
  27208. }
  27209. }
  27210. return null;
  27211. };
  27212. /**
  27213. * Gets a camera using its unique id
  27214. * @param uniqueId defines the unique id to look for
  27215. * @returns the camera or null if not found
  27216. */
  27217. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27218. for (var index = 0; index < this.cameras.length; index++) {
  27219. if (this.cameras[index].uniqueId === uniqueId) {
  27220. return this.cameras[index];
  27221. }
  27222. }
  27223. return null;
  27224. };
  27225. /**
  27226. * Gets a camera using its name
  27227. * @param name defines the camera's name
  27228. * @return the camera or null if none found.
  27229. */
  27230. Scene.prototype.getCameraByName = function (name) {
  27231. for (var index = 0; index < this.cameras.length; index++) {
  27232. if (this.cameras[index].name === name) {
  27233. return this.cameras[index];
  27234. }
  27235. }
  27236. return null;
  27237. };
  27238. /**
  27239. * Gets a bone using its id
  27240. * @param id defines the bone's id
  27241. * @return the bone or null if not found
  27242. */
  27243. Scene.prototype.getBoneByID = function (id) {
  27244. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27245. var skeleton = this.skeletons[skeletonIndex];
  27246. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27247. if (skeleton.bones[boneIndex].id === id) {
  27248. return skeleton.bones[boneIndex];
  27249. }
  27250. }
  27251. }
  27252. return null;
  27253. };
  27254. /**
  27255. * Gets a bone using its id
  27256. * @param name defines the bone's name
  27257. * @return the bone or null if not found
  27258. */
  27259. Scene.prototype.getBoneByName = function (name) {
  27260. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27261. var skeleton = this.skeletons[skeletonIndex];
  27262. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27263. if (skeleton.bones[boneIndex].name === name) {
  27264. return skeleton.bones[boneIndex];
  27265. }
  27266. }
  27267. }
  27268. return null;
  27269. };
  27270. /**
  27271. * Gets a light node using its name
  27272. * @param name defines the the light's name
  27273. * @return the light or null if none found.
  27274. */
  27275. Scene.prototype.getLightByName = function (name) {
  27276. for (var index = 0; index < this.lights.length; index++) {
  27277. if (this.lights[index].name === name) {
  27278. return this.lights[index];
  27279. }
  27280. }
  27281. return null;
  27282. };
  27283. /**
  27284. * Gets a light node using its id
  27285. * @param id defines the light's id
  27286. * @return the light or null if none found.
  27287. */
  27288. Scene.prototype.getLightByID = function (id) {
  27289. for (var index = 0; index < this.lights.length; index++) {
  27290. if (this.lights[index].id === id) {
  27291. return this.lights[index];
  27292. }
  27293. }
  27294. return null;
  27295. };
  27296. /**
  27297. * Gets a light node using its scene-generated unique ID
  27298. * @param uniqueId defines the light's unique id
  27299. * @return the light or null if none found.
  27300. */
  27301. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27302. for (var index = 0; index < this.lights.length; index++) {
  27303. if (this.lights[index].uniqueId === uniqueId) {
  27304. return this.lights[index];
  27305. }
  27306. }
  27307. return null;
  27308. };
  27309. /**
  27310. * Gets a particle system by id
  27311. * @param id defines the particle system id
  27312. * @return the corresponding system or null if none found
  27313. */
  27314. Scene.prototype.getParticleSystemByID = function (id) {
  27315. for (var index = 0; index < this.particleSystems.length; index++) {
  27316. if (this.particleSystems[index].id === id) {
  27317. return this.particleSystems[index];
  27318. }
  27319. }
  27320. return null;
  27321. };
  27322. /**
  27323. * Gets a geometry using its ID
  27324. * @param id defines the geometry's id
  27325. * @return the geometry or null if none found.
  27326. */
  27327. Scene.prototype.getGeometryByID = function (id) {
  27328. for (var index = 0; index < this.geometries.length; index++) {
  27329. if (this.geometries[index].id === id) {
  27330. return this.geometries[index];
  27331. }
  27332. }
  27333. return null;
  27334. };
  27335. /**
  27336. * Add a new geometry to this scene
  27337. * @param geometry defines the geometry to be added to the scene.
  27338. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27339. * @return a boolean defining if the geometry was added or not
  27340. */
  27341. Scene.prototype.pushGeometry = function (geometry, force) {
  27342. if (!force && this.getGeometryByID(geometry.id)) {
  27343. return false;
  27344. }
  27345. this.geometries.push(geometry);
  27346. //notify the collision coordinator
  27347. if (this.collisionCoordinator) {
  27348. this.collisionCoordinator.onGeometryAdded(geometry);
  27349. }
  27350. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27351. return true;
  27352. };
  27353. /**
  27354. * Removes an existing geometry
  27355. * @param geometry defines the geometry to be removed from the scene
  27356. * @return a boolean defining if the geometry was removed or not
  27357. */
  27358. Scene.prototype.removeGeometry = function (geometry) {
  27359. var index = this.geometries.indexOf(geometry);
  27360. if (index > -1) {
  27361. this.geometries.splice(index, 1);
  27362. //notify the collision coordinator
  27363. if (this.collisionCoordinator) {
  27364. this.collisionCoordinator.onGeometryDeleted(geometry);
  27365. }
  27366. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27367. return true;
  27368. }
  27369. return false;
  27370. };
  27371. /**
  27372. * Gets the list of geometries attached to the scene
  27373. * @returns an array of Geometry
  27374. */
  27375. Scene.prototype.getGeometries = function () {
  27376. return this.geometries;
  27377. };
  27378. /**
  27379. * Gets the first added mesh found of a given ID
  27380. * @param id defines the id to search for
  27381. * @return the mesh found or null if not found at all
  27382. */
  27383. Scene.prototype.getMeshByID = function (id) {
  27384. for (var index = 0; index < this.meshes.length; index++) {
  27385. if (this.meshes[index].id === id) {
  27386. return this.meshes[index];
  27387. }
  27388. }
  27389. return null;
  27390. };
  27391. /**
  27392. * Gets a list of meshes using their id
  27393. * @param id defines the id to search for
  27394. * @returns a list of meshes
  27395. */
  27396. Scene.prototype.getMeshesByID = function (id) {
  27397. return this.meshes.filter(function (m) {
  27398. return m.id === id;
  27399. });
  27400. };
  27401. /**
  27402. * Gets the first added transform node found of a given ID
  27403. * @param id defines the id to search for
  27404. * @return the found transform node or null if not found at all.
  27405. */
  27406. Scene.prototype.getTransformNodeByID = function (id) {
  27407. for (var index = 0; index < this.transformNodes.length; index++) {
  27408. if (this.transformNodes[index].id === id) {
  27409. return this.transformNodes[index];
  27410. }
  27411. }
  27412. return null;
  27413. };
  27414. /**
  27415. * Gets a list of transform nodes using their id
  27416. * @param id defines the id to search for
  27417. * @returns a list of transform nodes
  27418. */
  27419. Scene.prototype.getTransformNodesByID = function (id) {
  27420. return this.transformNodes.filter(function (m) {
  27421. return m.id === id;
  27422. });
  27423. };
  27424. /**
  27425. * Gets a mesh with its auto-generated unique id
  27426. * @param uniqueId defines the unique id to search for
  27427. * @return the found mesh or null if not found at all.
  27428. */
  27429. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27430. for (var index = 0; index < this.meshes.length; index++) {
  27431. if (this.meshes[index].uniqueId === uniqueId) {
  27432. return this.meshes[index];
  27433. }
  27434. }
  27435. return null;
  27436. };
  27437. /**
  27438. * Gets a the last added mesh using a given id
  27439. * @param id defines the id to search for
  27440. * @return the found mesh or null if not found at all.
  27441. */
  27442. Scene.prototype.getLastMeshByID = function (id) {
  27443. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27444. if (this.meshes[index].id === id) {
  27445. return this.meshes[index];
  27446. }
  27447. }
  27448. return null;
  27449. };
  27450. /**
  27451. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27452. * @param id defines the id to search for
  27453. * @return the found node or null if not found at all
  27454. */
  27455. Scene.prototype.getLastEntryByID = function (id) {
  27456. var index;
  27457. for (index = this.meshes.length - 1; index >= 0; index--) {
  27458. if (this.meshes[index].id === id) {
  27459. return this.meshes[index];
  27460. }
  27461. }
  27462. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27463. if (this.transformNodes[index].id === id) {
  27464. return this.transformNodes[index];
  27465. }
  27466. }
  27467. for (index = this.cameras.length - 1; index >= 0; index--) {
  27468. if (this.cameras[index].id === id) {
  27469. return this.cameras[index];
  27470. }
  27471. }
  27472. for (index = this.lights.length - 1; index >= 0; index--) {
  27473. if (this.lights[index].id === id) {
  27474. return this.lights[index];
  27475. }
  27476. }
  27477. return null;
  27478. };
  27479. /**
  27480. * Gets a node (Mesh, Camera, Light) using a given id
  27481. * @param id defines the id to search for
  27482. * @return the found node or null if not found at all
  27483. */
  27484. Scene.prototype.getNodeByID = function (id) {
  27485. var mesh = this.getMeshByID(id);
  27486. if (mesh) {
  27487. return mesh;
  27488. }
  27489. var light = this.getLightByID(id);
  27490. if (light) {
  27491. return light;
  27492. }
  27493. var camera = this.getCameraByID(id);
  27494. if (camera) {
  27495. return camera;
  27496. }
  27497. var bone = this.getBoneByID(id);
  27498. return bone;
  27499. };
  27500. /**
  27501. * Gets a node (Mesh, Camera, Light) using a given name
  27502. * @param name defines the name to search for
  27503. * @return the found node or null if not found at all.
  27504. */
  27505. Scene.prototype.getNodeByName = function (name) {
  27506. var mesh = this.getMeshByName(name);
  27507. if (mesh) {
  27508. return mesh;
  27509. }
  27510. var light = this.getLightByName(name);
  27511. if (light) {
  27512. return light;
  27513. }
  27514. var camera = this.getCameraByName(name);
  27515. if (camera) {
  27516. return camera;
  27517. }
  27518. var bone = this.getBoneByName(name);
  27519. return bone;
  27520. };
  27521. /**
  27522. * Gets a mesh using a given name
  27523. * @param name defines the name to search for
  27524. * @return the found mesh or null if not found at all.
  27525. */
  27526. Scene.prototype.getMeshByName = function (name) {
  27527. for (var index = 0; index < this.meshes.length; index++) {
  27528. if (this.meshes[index].name === name) {
  27529. return this.meshes[index];
  27530. }
  27531. }
  27532. return null;
  27533. };
  27534. /**
  27535. * Gets a transform node using a given name
  27536. * @param name defines the name to search for
  27537. * @return the found transform node or null if not found at all.
  27538. */
  27539. Scene.prototype.getTransformNodeByName = function (name) {
  27540. for (var index = 0; index < this.transformNodes.length; index++) {
  27541. if (this.transformNodes[index].name === name) {
  27542. return this.transformNodes[index];
  27543. }
  27544. }
  27545. return null;
  27546. };
  27547. /**
  27548. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27549. * @param id defines the id to search for
  27550. * @return the found skeleton or null if not found at all.
  27551. */
  27552. Scene.prototype.getLastSkeletonByID = function (id) {
  27553. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27554. if (this.skeletons[index].id === id) {
  27555. return this.skeletons[index];
  27556. }
  27557. }
  27558. return null;
  27559. };
  27560. /**
  27561. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27562. * @param id defines the id to search for
  27563. * @return the found skeleton or null if not found at all.
  27564. */
  27565. Scene.prototype.getSkeletonById = function (id) {
  27566. for (var index = 0; index < this.skeletons.length; index++) {
  27567. if (this.skeletons[index].id === id) {
  27568. return this.skeletons[index];
  27569. }
  27570. }
  27571. return null;
  27572. };
  27573. /**
  27574. * Gets a skeleton using a given name
  27575. * @param name defines the name to search for
  27576. * @return the found skeleton or null if not found at all.
  27577. */
  27578. Scene.prototype.getSkeletonByName = function (name) {
  27579. for (var index = 0; index < this.skeletons.length; index++) {
  27580. if (this.skeletons[index].name === name) {
  27581. return this.skeletons[index];
  27582. }
  27583. }
  27584. return null;
  27585. };
  27586. /**
  27587. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27588. * @param id defines the id to search for
  27589. * @return the found morph target manager or null if not found at all.
  27590. */
  27591. Scene.prototype.getMorphTargetManagerById = function (id) {
  27592. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27593. if (this.morphTargetManagers[index].uniqueId === id) {
  27594. return this.morphTargetManagers[index];
  27595. }
  27596. }
  27597. return null;
  27598. };
  27599. /**
  27600. * Gets a boolean indicating if the given mesh is active
  27601. * @param mesh defines the mesh to look for
  27602. * @returns true if the mesh is in the active list
  27603. */
  27604. Scene.prototype.isActiveMesh = function (mesh) {
  27605. return (this._activeMeshes.indexOf(mesh) !== -1);
  27606. };
  27607. Object.defineProperty(Scene.prototype, "uid", {
  27608. /**
  27609. * Return a unique id as a string which can serve as an identifier for the scene
  27610. */
  27611. get: function () {
  27612. if (!this._uid) {
  27613. this._uid = BABYLON.Tools.RandomId();
  27614. }
  27615. return this._uid;
  27616. },
  27617. enumerable: true,
  27618. configurable: true
  27619. });
  27620. /**
  27621. * Add an externaly attached data from its key.
  27622. * This method call will fail and return false, if such key already exists.
  27623. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27624. * @param key the unique key that identifies the data
  27625. * @param data the data object to associate to the key for this Engine instance
  27626. * @return true if no such key were already present and the data was added successfully, false otherwise
  27627. */
  27628. Scene.prototype.addExternalData = function (key, data) {
  27629. if (!this._externalData) {
  27630. this._externalData = new BABYLON.StringDictionary();
  27631. }
  27632. return this._externalData.add(key, data);
  27633. };
  27634. /**
  27635. * Get an externaly attached data from its key
  27636. * @param key the unique key that identifies the data
  27637. * @return the associated data, if present (can be null), or undefined if not present
  27638. */
  27639. Scene.prototype.getExternalData = function (key) {
  27640. if (!this._externalData) {
  27641. return null;
  27642. }
  27643. return this._externalData.get(key);
  27644. };
  27645. /**
  27646. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27647. * @param key the unique key that identifies the data
  27648. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27649. * @return the associated data, can be null if the factory returned null.
  27650. */
  27651. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27652. if (!this._externalData) {
  27653. this._externalData = new BABYLON.StringDictionary();
  27654. }
  27655. return this._externalData.getOrAddWithFactory(key, factory);
  27656. };
  27657. /**
  27658. * Remove an externaly attached data from the Engine instance
  27659. * @param key the unique key that identifies the data
  27660. * @return true if the data was successfully removed, false if it doesn't exist
  27661. */
  27662. Scene.prototype.removeExternalData = function (key) {
  27663. return this._externalData.remove(key);
  27664. };
  27665. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27666. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27667. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27668. var step = _a[_i];
  27669. step.action(mesh, subMesh);
  27670. }
  27671. var material = subMesh.getMaterial();
  27672. if (material !== null && material !== undefined) {
  27673. // Render targets
  27674. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27675. if (this._processedMaterials.indexOf(material) === -1) {
  27676. this._processedMaterials.push(material);
  27677. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27678. }
  27679. }
  27680. // Dispatch
  27681. this._activeIndices.addCount(subMesh.indexCount, false);
  27682. this._renderingManager.dispatch(subMesh, mesh, material);
  27683. }
  27684. }
  27685. };
  27686. /**
  27687. * Clear the processed materials smart array preventing retention point in material dispose.
  27688. */
  27689. Scene.prototype.freeProcessedMaterials = function () {
  27690. this._processedMaterials.dispose();
  27691. };
  27692. /**
  27693. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27694. */
  27695. Scene.prototype.freeActiveMeshes = function () {
  27696. this._activeMeshes.dispose();
  27697. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27698. this.activeCamera._activeMeshes.dispose();
  27699. }
  27700. if (this.activeCameras) {
  27701. for (var i = 0; i < this.activeCameras.length; i++) {
  27702. var activeCamera = this.activeCameras[i];
  27703. if (activeCamera && activeCamera._activeMeshes) {
  27704. activeCamera._activeMeshes.dispose();
  27705. }
  27706. }
  27707. }
  27708. };
  27709. /**
  27710. * Clear the info related to rendering groups preventing retention points during dispose.
  27711. */
  27712. Scene.prototype.freeRenderingGroups = function () {
  27713. if (this._renderingManager) {
  27714. this._renderingManager.freeRenderingGroups();
  27715. }
  27716. if (this.textures) {
  27717. for (var i = 0; i < this.textures.length; i++) {
  27718. var texture = this.textures[i];
  27719. if (texture && texture.renderList) {
  27720. texture.freeRenderingGroups();
  27721. }
  27722. }
  27723. }
  27724. };
  27725. /** @hidden */
  27726. Scene.prototype._isInIntermediateRendering = function () {
  27727. return this._intermediateRendering;
  27728. };
  27729. /**
  27730. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27731. * @returns the current scene
  27732. */
  27733. Scene.prototype.freezeActiveMeshes = function () {
  27734. if (!this.activeCamera) {
  27735. return this;
  27736. }
  27737. if (!this._frustumPlanes) {
  27738. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27739. }
  27740. this._evaluateActiveMeshes();
  27741. this._activeMeshesFrozen = true;
  27742. return this;
  27743. };
  27744. /**
  27745. * Use this function to restart evaluating active meshes on every frame
  27746. * @returns the current scene
  27747. */
  27748. Scene.prototype.unfreezeActiveMeshes = function () {
  27749. this._activeMeshesFrozen = false;
  27750. return this;
  27751. };
  27752. Scene.prototype._evaluateActiveMeshes = function () {
  27753. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27754. return;
  27755. }
  27756. if (!this.activeCamera) {
  27757. return;
  27758. }
  27759. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27760. this.activeCamera._activeMeshes.reset();
  27761. this._activeMeshes.reset();
  27762. this._renderingManager.reset();
  27763. this._processedMaterials.reset();
  27764. this._activeParticleSystems.reset();
  27765. this._activeSkeletons.reset();
  27766. this._softwareSkinnedMeshes.reset();
  27767. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27768. var step = _a[_i];
  27769. step.action();
  27770. }
  27771. // Determine mesh candidates
  27772. var meshes = this.getActiveMeshCandidates();
  27773. // Check each mesh
  27774. var len = meshes.length;
  27775. for (var i = 0; i < len; i++) {
  27776. var mesh = meshes.data[i];
  27777. if (mesh.isBlocked) {
  27778. continue;
  27779. }
  27780. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27781. if (!mesh.isReady() || !mesh.isEnabled()) {
  27782. continue;
  27783. }
  27784. mesh.computeWorldMatrix();
  27785. // Intersections
  27786. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27787. this._meshesForIntersections.pushNoDuplicate(mesh);
  27788. }
  27789. // Switch to current LOD
  27790. var meshLOD = mesh.getLOD(this.activeCamera);
  27791. if (meshLOD === undefined || meshLOD === null) {
  27792. continue;
  27793. }
  27794. mesh._preActivate();
  27795. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27796. this._activeMeshes.push(mesh);
  27797. this.activeCamera._activeMeshes.push(mesh);
  27798. mesh._activate(this._renderId);
  27799. if (meshLOD !== mesh) {
  27800. meshLOD._activate(this._renderId);
  27801. }
  27802. this._activeMesh(mesh, meshLOD);
  27803. }
  27804. }
  27805. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27806. // Particle systems
  27807. if (this.particlesEnabled) {
  27808. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27809. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27810. var particleSystem = this.particleSystems[particleIndex];
  27811. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27812. continue;
  27813. }
  27814. var emitter = particleSystem.emitter;
  27815. if (!emitter.position || emitter.isEnabled()) {
  27816. this._activeParticleSystems.push(particleSystem);
  27817. particleSystem.animate();
  27818. this._renderingManager.dispatchParticles(particleSystem);
  27819. }
  27820. }
  27821. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27822. }
  27823. };
  27824. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27825. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27826. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27827. mesh.skeleton.prepare();
  27828. }
  27829. if (!mesh.computeBonesUsingShaders) {
  27830. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27831. }
  27832. }
  27833. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27834. var step = _a[_i];
  27835. step.action(sourceMesh, mesh);
  27836. }
  27837. if (mesh !== undefined && mesh !== null
  27838. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27839. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27840. var len = subMeshes.length;
  27841. for (var i = 0; i < len; i++) {
  27842. var subMesh = subMeshes.data[i];
  27843. this._evaluateSubMesh(subMesh, mesh);
  27844. }
  27845. }
  27846. };
  27847. /**
  27848. * Update the transform matrix to update from the current active camera
  27849. * @param force defines a boolean used to force the update even if cache is up to date
  27850. */
  27851. Scene.prototype.updateTransformMatrix = function (force) {
  27852. if (!this.activeCamera) {
  27853. return;
  27854. }
  27855. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27856. };
  27857. /**
  27858. * 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)
  27859. * @param alternateCamera defines the camera to use
  27860. */
  27861. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27862. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27863. };
  27864. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27865. if (camera && camera._skipRendering) {
  27866. return;
  27867. }
  27868. var engine = this._engine;
  27869. this.activeCamera = camera;
  27870. if (!this.activeCamera)
  27871. throw new Error("Active camera not set");
  27872. // Viewport
  27873. engine.setViewport(this.activeCamera.viewport);
  27874. // Camera
  27875. this.resetCachedMaterial();
  27876. this._renderId++;
  27877. this.updateTransformMatrix();
  27878. if (camera._alternateCamera) {
  27879. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27880. this._alternateRendering = true;
  27881. }
  27882. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27883. // Meshes
  27884. this._evaluateActiveMeshes();
  27885. // Software skinning
  27886. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27887. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27888. mesh.applySkeleton(mesh.skeleton);
  27889. }
  27890. // Render targets
  27891. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27892. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27893. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27894. }
  27895. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27896. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27897. }
  27898. // Collects render targets from external components.
  27899. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27900. var step = _a[_i];
  27901. step.action(this._renderTargets);
  27902. }
  27903. if (this.renderTargetsEnabled) {
  27904. this._intermediateRendering = true;
  27905. if (this._renderTargets.length > 0) {
  27906. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27907. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27908. var renderTarget = this._renderTargets.data[renderIndex];
  27909. if (renderTarget._shouldRender()) {
  27910. this._renderId++;
  27911. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27912. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27913. }
  27914. }
  27915. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27916. this._renderId++;
  27917. }
  27918. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27919. var step = _c[_b];
  27920. step.action(this.activeCamera);
  27921. }
  27922. this._intermediateRendering = false;
  27923. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27924. }
  27925. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27926. // Prepare Frame
  27927. if (this.postProcessManager) {
  27928. this.postProcessManager._prepareFrame();
  27929. }
  27930. // Before Camera Draw
  27931. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27932. var step = _e[_d];
  27933. step.action(this.activeCamera);
  27934. }
  27935. // Render
  27936. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27937. this._renderingManager.render(null, null, true, true);
  27938. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27939. // After Camera Draw
  27940. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27941. var step = _g[_f];
  27942. step.action(this.activeCamera);
  27943. }
  27944. // Finalize frame
  27945. if (this.postProcessManager) {
  27946. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27947. }
  27948. // Reset some special arrays
  27949. this._renderTargets.reset();
  27950. this._alternateRendering = false;
  27951. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27952. };
  27953. Scene.prototype._processSubCameras = function (camera) {
  27954. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27955. this._renderForCamera(camera);
  27956. return;
  27957. }
  27958. // rig cameras
  27959. for (var index = 0; index < camera._rigCameras.length; index++) {
  27960. this._renderForCamera(camera._rigCameras[index], camera);
  27961. }
  27962. this.activeCamera = camera;
  27963. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27964. };
  27965. Scene.prototype._checkIntersections = function () {
  27966. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27967. var sourceMesh = this._meshesForIntersections.data[index];
  27968. if (!sourceMesh.actionManager) {
  27969. continue;
  27970. }
  27971. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27972. var action = sourceMesh.actionManager.actions[actionIndex];
  27973. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27974. var parameters = action.getTriggerParameter();
  27975. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27976. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27977. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27978. if (areIntersecting && currentIntersectionInProgress === -1) {
  27979. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27980. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27981. sourceMesh._intersectionsInProgress.push(otherMesh);
  27982. }
  27983. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27984. sourceMesh._intersectionsInProgress.push(otherMesh);
  27985. }
  27986. }
  27987. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27988. //They intersected, and now they don't.
  27989. //is this trigger an exit trigger? execute an event.
  27990. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27991. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27992. }
  27993. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27994. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27995. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27996. return otherMesh === parameterMesh;
  27997. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27998. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27999. }
  28000. }
  28001. }
  28002. }
  28003. }
  28004. };
  28005. /** @hidden */
  28006. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28007. // Do nothing. Code will be replaced if physics engine component is referenced
  28008. };
  28009. /**
  28010. * Render the scene
  28011. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28012. */
  28013. Scene.prototype.render = function (updateCameras) {
  28014. if (updateCameras === void 0) { updateCameras = true; }
  28015. if (this.isDisposed) {
  28016. return;
  28017. }
  28018. this._frameId++;
  28019. // Register components that have been associated lately to the scene.
  28020. this._registerTransientComponents();
  28021. this._activeParticles.fetchNewFrame();
  28022. this._totalVertices.fetchNewFrame();
  28023. this._activeIndices.fetchNewFrame();
  28024. this._activeBones.fetchNewFrame();
  28025. this._meshesForIntersections.reset();
  28026. this.resetCachedMaterial();
  28027. this.onBeforeAnimationsObservable.notifyObservers(this);
  28028. // Actions
  28029. if (this.actionManager) {
  28030. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28031. }
  28032. if (this._engine.isDeterministicLockStep()) {
  28033. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28034. var defaultFPS = (60.0 / 1000.0);
  28035. var defaultFrameTime = this.getDeterministicFrameTime();
  28036. var stepsTaken = 0;
  28037. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28038. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28039. internalSteps = Math.min(internalSteps, maxSubSteps);
  28040. do {
  28041. this.onBeforeStepObservable.notifyObservers(this);
  28042. // Animations
  28043. this._animationRatio = defaultFrameTime * defaultFPS;
  28044. this._animate();
  28045. this.onAfterAnimationsObservable.notifyObservers(this);
  28046. // Physics
  28047. this._advancePhysicsEngineStep(defaultFrameTime);
  28048. this.onAfterStepObservable.notifyObservers(this);
  28049. this._currentStepId++;
  28050. stepsTaken++;
  28051. deltaTime -= defaultFrameTime;
  28052. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28053. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28054. }
  28055. else {
  28056. // Animations
  28057. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28058. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28059. this._animate();
  28060. this.onAfterAnimationsObservable.notifyObservers(this);
  28061. // Physics
  28062. this._advancePhysicsEngineStep(deltaTime);
  28063. }
  28064. // Before camera update steps
  28065. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28066. var step = _a[_i];
  28067. step.action();
  28068. }
  28069. // Update Cameras
  28070. if (updateCameras) {
  28071. if (this.activeCameras.length > 0) {
  28072. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28073. var camera = this.activeCameras[cameraIndex];
  28074. camera.update();
  28075. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28076. // rig cameras
  28077. for (var index = 0; index < camera._rigCameras.length; index++) {
  28078. camera._rigCameras[index].update();
  28079. }
  28080. }
  28081. }
  28082. }
  28083. else if (this.activeCamera) {
  28084. this.activeCamera.update();
  28085. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28086. // rig cameras
  28087. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28088. this.activeCamera._rigCameras[index].update();
  28089. }
  28090. }
  28091. }
  28092. }
  28093. // Before render
  28094. this.onBeforeRenderObservable.notifyObservers(this);
  28095. // Customs render targets
  28096. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28097. var engine = this.getEngine();
  28098. var currentActiveCamera = this.activeCamera;
  28099. if (this.renderTargetsEnabled) {
  28100. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28101. this._intermediateRendering = true;
  28102. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28103. var renderTarget = this.customRenderTargets[customIndex];
  28104. if (renderTarget._shouldRender()) {
  28105. this._renderId++;
  28106. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28107. if (!this.activeCamera)
  28108. throw new Error("Active camera not set");
  28109. // Viewport
  28110. engine.setViewport(this.activeCamera.viewport);
  28111. // Camera
  28112. this.updateTransformMatrix();
  28113. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28114. }
  28115. }
  28116. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28117. this._intermediateRendering = false;
  28118. this._renderId++;
  28119. }
  28120. // Restore back buffer
  28121. if (this.customRenderTargets.length > 0) {
  28122. engine.restoreDefaultFramebuffer();
  28123. }
  28124. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28125. this.activeCamera = currentActiveCamera;
  28126. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28127. var step = _c[_b];
  28128. step.action();
  28129. }
  28130. // Clear
  28131. if (this.autoClearDepthAndStencil || this.autoClear) {
  28132. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28133. }
  28134. // Collects render targets from external components.
  28135. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28136. var step = _e[_d];
  28137. step.action(this._renderTargets);
  28138. }
  28139. // Multi-cameras?
  28140. if (this.activeCameras.length > 0) {
  28141. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28142. if (cameraIndex > 0) {
  28143. this._engine.clear(null, false, true, true);
  28144. }
  28145. this._processSubCameras(this.activeCameras[cameraIndex]);
  28146. }
  28147. }
  28148. else {
  28149. if (!this.activeCamera) {
  28150. throw new Error("No camera defined");
  28151. }
  28152. this._processSubCameras(this.activeCamera);
  28153. }
  28154. // Intersection checks
  28155. this._checkIntersections();
  28156. // Executes the after render stage actions.
  28157. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28158. var step = _g[_f];
  28159. step.action();
  28160. }
  28161. // After render
  28162. if (this.afterRender) {
  28163. this.afterRender();
  28164. }
  28165. this.onAfterRenderObservable.notifyObservers(this);
  28166. // Cleaning
  28167. if (this._toBeDisposed.length) {
  28168. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28169. var data = this._toBeDisposed[index];
  28170. if (data) {
  28171. data.dispose();
  28172. }
  28173. }
  28174. this._toBeDisposed = [];
  28175. }
  28176. if (this.dumpNextRenderTargets) {
  28177. this.dumpNextRenderTargets = false;
  28178. }
  28179. this._activeBones.addCount(0, true);
  28180. this._activeIndices.addCount(0, true);
  28181. this._activeParticles.addCount(0, true);
  28182. };
  28183. /**
  28184. * Freeze all materials
  28185. * A frozen material will not be updatable but should be faster to render
  28186. */
  28187. Scene.prototype.freezeMaterials = function () {
  28188. for (var i = 0; i < this.materials.length; i++) {
  28189. this.materials[i].freeze();
  28190. }
  28191. };
  28192. /**
  28193. * Unfreeze all materials
  28194. * A frozen material will not be updatable but should be faster to render
  28195. */
  28196. Scene.prototype.unfreezeMaterials = function () {
  28197. for (var i = 0; i < this.materials.length; i++) {
  28198. this.materials[i].unfreeze();
  28199. }
  28200. };
  28201. /**
  28202. * Releases all held ressources
  28203. */
  28204. Scene.prototype.dispose = function () {
  28205. this.beforeRender = null;
  28206. this.afterRender = null;
  28207. this.skeletons = [];
  28208. this.morphTargetManagers = [];
  28209. this._transientComponents = [];
  28210. this._isReadyForMeshStage.clear();
  28211. this._beforeEvaluateActiveMeshStage.clear();
  28212. this._evaluateSubMeshStage.clear();
  28213. this._activeMeshStage.clear();
  28214. this._cameraDrawRenderTargetStage.clear();
  28215. this._beforeCameraDrawStage.clear();
  28216. this._beforeRenderingGroupDrawStage.clear();
  28217. this._beforeRenderingMeshStage.clear();
  28218. this._afterRenderingMeshStage.clear();
  28219. this._afterRenderingGroupDrawStage.clear();
  28220. this._afterCameraDrawStage.clear();
  28221. this._afterRenderStage.clear();
  28222. this._beforeCameraUpdateStage.clear();
  28223. this._beforeClearStage.clear();
  28224. this._gatherRenderTargetsStage.clear();
  28225. this._gatherActiveCameraRenderTargetsStage.clear();
  28226. this._pointerMoveStage.clear();
  28227. this._pointerDownStage.clear();
  28228. this._pointerUpStage.clear();
  28229. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28230. var component = _a[_i];
  28231. component.dispose();
  28232. }
  28233. this.importedMeshesFiles = new Array();
  28234. this.stopAllAnimations();
  28235. this.resetCachedMaterial();
  28236. // Smart arrays
  28237. if (this.activeCamera) {
  28238. this.activeCamera._activeMeshes.dispose();
  28239. this.activeCamera = null;
  28240. }
  28241. this._activeMeshes.dispose();
  28242. this._renderingManager.dispose();
  28243. this._processedMaterials.dispose();
  28244. this._activeParticleSystems.dispose();
  28245. this._activeSkeletons.dispose();
  28246. this._softwareSkinnedMeshes.dispose();
  28247. this._renderTargets.dispose();
  28248. this._registeredForLateAnimationBindings.dispose();
  28249. this._meshesForIntersections.dispose();
  28250. this._toBeDisposed = [];
  28251. // Abort active requests
  28252. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28253. var request = _c[_b];
  28254. request.abort();
  28255. }
  28256. // Events
  28257. this.onDisposeObservable.notifyObservers(this);
  28258. this.onDisposeObservable.clear();
  28259. this.onBeforeRenderObservable.clear();
  28260. this.onAfterRenderObservable.clear();
  28261. this.onBeforeRenderTargetsRenderObservable.clear();
  28262. this.onAfterRenderTargetsRenderObservable.clear();
  28263. this.onAfterStepObservable.clear();
  28264. this.onBeforeStepObservable.clear();
  28265. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28266. this.onAfterActiveMeshesEvaluationObservable.clear();
  28267. this.onBeforeParticlesRenderingObservable.clear();
  28268. this.onAfterParticlesRenderingObservable.clear();
  28269. this.onBeforeDrawPhaseObservable.clear();
  28270. this.onAfterDrawPhaseObservable.clear();
  28271. this.onBeforeAnimationsObservable.clear();
  28272. this.onAfterAnimationsObservable.clear();
  28273. this.onDataLoadedObservable.clear();
  28274. this.onBeforeRenderingGroupObservable.clear();
  28275. this.onAfterRenderingGroupObservable.clear();
  28276. this.onMeshImportedObservable.clear();
  28277. this.onBeforeCameraRenderObservable.clear();
  28278. this.onAfterCameraRenderObservable.clear();
  28279. this.onReadyObservable.clear();
  28280. this.onNewCameraAddedObservable.clear();
  28281. this.onCameraRemovedObservable.clear();
  28282. this.onNewLightAddedObservable.clear();
  28283. this.onLightRemovedObservable.clear();
  28284. this.onNewGeometryAddedObservable.clear();
  28285. this.onGeometryRemovedObservable.clear();
  28286. this.onNewTransformNodeAddedObservable.clear();
  28287. this.onTransformNodeRemovedObservable.clear();
  28288. this.onNewMeshAddedObservable.clear();
  28289. this.onMeshRemovedObservable.clear();
  28290. this.onNewMaterialAddedObservable.clear();
  28291. this.onMaterialRemovedObservable.clear();
  28292. this.onNewTextureAddedObservable.clear();
  28293. this.onTextureRemovedObservable.clear();
  28294. this.onPrePointerObservable.clear();
  28295. this.onPointerObservable.clear();
  28296. this.onPreKeyboardObservable.clear();
  28297. this.onKeyboardObservable.clear();
  28298. this.detachControl();
  28299. // Detach cameras
  28300. var canvas = this._engine.getRenderingCanvas();
  28301. if (canvas) {
  28302. var index;
  28303. for (index = 0; index < this.cameras.length; index++) {
  28304. this.cameras[index].detachControl(canvas);
  28305. }
  28306. }
  28307. // Release animation groups
  28308. while (this.animationGroups.length) {
  28309. this.animationGroups[0].dispose();
  28310. }
  28311. // Release lights
  28312. while (this.lights.length) {
  28313. this.lights[0].dispose();
  28314. }
  28315. // Release meshes
  28316. while (this.meshes.length) {
  28317. this.meshes[0].dispose(true);
  28318. }
  28319. while (this.transformNodes.length) {
  28320. this.removeTransformNode(this.transformNodes[0]);
  28321. }
  28322. // Release cameras
  28323. while (this.cameras.length) {
  28324. this.cameras[0].dispose();
  28325. }
  28326. // Release materials
  28327. if (this.defaultMaterial) {
  28328. this.defaultMaterial.dispose();
  28329. }
  28330. while (this.multiMaterials.length) {
  28331. this.multiMaterials[0].dispose();
  28332. }
  28333. while (this.materials.length) {
  28334. this.materials[0].dispose();
  28335. }
  28336. // Release particles
  28337. while (this.particleSystems.length) {
  28338. this.particleSystems[0].dispose();
  28339. }
  28340. // Release postProcesses
  28341. while (this.postProcesses.length) {
  28342. this.postProcesses[0].dispose();
  28343. }
  28344. // Release textures
  28345. while (this.textures.length) {
  28346. this.textures[0].dispose();
  28347. }
  28348. // Release UBO
  28349. this._sceneUbo.dispose();
  28350. if (this._alternateSceneUbo) {
  28351. this._alternateSceneUbo.dispose();
  28352. }
  28353. // Post-processes
  28354. this.postProcessManager.dispose();
  28355. // Remove from engine
  28356. index = this._engine.scenes.indexOf(this);
  28357. if (index > -1) {
  28358. this._engine.scenes.splice(index, 1);
  28359. }
  28360. this._engine.wipeCaches(true);
  28361. this._isDisposed = true;
  28362. };
  28363. Object.defineProperty(Scene.prototype, "isDisposed", {
  28364. /**
  28365. * Gets if the scene is already disposed
  28366. */
  28367. get: function () {
  28368. return this._isDisposed;
  28369. },
  28370. enumerable: true,
  28371. configurable: true
  28372. });
  28373. /**
  28374. * Call this function to reduce memory footprint of the scene.
  28375. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28376. */
  28377. Scene.prototype.clearCachedVertexData = function () {
  28378. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28379. var mesh = this.meshes[meshIndex];
  28380. var geometry = mesh.geometry;
  28381. if (geometry) {
  28382. geometry._indices = [];
  28383. for (var vbName in geometry._vertexBuffers) {
  28384. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28385. continue;
  28386. }
  28387. geometry._vertexBuffers[vbName]._buffer._data = null;
  28388. }
  28389. }
  28390. }
  28391. };
  28392. /**
  28393. * This function will remove the local cached buffer data from texture.
  28394. * It will save memory but will prevent the texture from being rebuilt
  28395. */
  28396. Scene.prototype.cleanCachedTextureBuffer = function () {
  28397. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28398. var baseTexture = _a[_i];
  28399. var buffer = baseTexture._buffer;
  28400. if (buffer) {
  28401. baseTexture._buffer = null;
  28402. }
  28403. }
  28404. };
  28405. /**
  28406. * Get the world extend vectors with an optional filter
  28407. *
  28408. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28409. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28410. */
  28411. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28412. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28413. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28414. filterPredicate = filterPredicate || (function () { return true; });
  28415. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28416. mesh.computeWorldMatrix(true);
  28417. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28418. return;
  28419. }
  28420. var boundingInfo = mesh.getBoundingInfo();
  28421. var minBox = boundingInfo.boundingBox.minimumWorld;
  28422. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28423. BABYLON.Tools.CheckExtends(minBox, min, max);
  28424. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28425. });
  28426. return {
  28427. min: min,
  28428. max: max
  28429. };
  28430. };
  28431. // Picking
  28432. /**
  28433. * Creates a ray that can be used to pick in the scene
  28434. * @param x defines the x coordinate of the origin (on-screen)
  28435. * @param y defines the y coordinate of the origin (on-screen)
  28436. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28437. * @param camera defines the camera to use for the picking
  28438. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28439. * @returns a Ray
  28440. */
  28441. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28442. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28443. var result = BABYLON.Ray.Zero();
  28444. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28445. return result;
  28446. };
  28447. /**
  28448. * Creates a ray that can be used to pick in the scene
  28449. * @param x defines the x coordinate of the origin (on-screen)
  28450. * @param y defines the y coordinate of the origin (on-screen)
  28451. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28452. * @param result defines the ray where to store the picking ray
  28453. * @param camera defines the camera to use for the picking
  28454. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28455. * @returns the current scene
  28456. */
  28457. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28458. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28459. var engine = this._engine;
  28460. if (!camera) {
  28461. if (!this.activeCamera)
  28462. throw new Error("Active camera not set");
  28463. camera = this.activeCamera;
  28464. }
  28465. var cameraViewport = camera.viewport;
  28466. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28467. // Moving coordinates to local viewport world
  28468. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28469. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28470. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28471. return this;
  28472. };
  28473. /**
  28474. * Creates a ray that can be used to pick in the scene
  28475. * @param x defines the x coordinate of the origin (on-screen)
  28476. * @param y defines the y coordinate of the origin (on-screen)
  28477. * @param camera defines the camera to use for the picking
  28478. * @returns a Ray
  28479. */
  28480. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28481. var result = BABYLON.Ray.Zero();
  28482. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28483. return result;
  28484. };
  28485. /**
  28486. * Creates a ray that can be used to pick in the scene
  28487. * @param x defines the x coordinate of the origin (on-screen)
  28488. * @param y defines the y coordinate of the origin (on-screen)
  28489. * @param result defines the ray where to store the picking ray
  28490. * @param camera defines the camera to use for the picking
  28491. * @returns the current scene
  28492. */
  28493. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28494. if (!BABYLON.PickingInfo) {
  28495. return this;
  28496. }
  28497. var engine = this._engine;
  28498. if (!camera) {
  28499. if (!this.activeCamera)
  28500. throw new Error("Active camera not set");
  28501. camera = this.activeCamera;
  28502. }
  28503. var cameraViewport = camera.viewport;
  28504. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28505. var identity = BABYLON.Matrix.Identity();
  28506. // Moving coordinates to local viewport world
  28507. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28508. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28509. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28510. return this;
  28511. };
  28512. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28513. if (!BABYLON.PickingInfo) {
  28514. return null;
  28515. }
  28516. var pickingInfo = null;
  28517. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28518. var mesh = this.meshes[meshIndex];
  28519. if (predicate) {
  28520. if (!predicate(mesh)) {
  28521. continue;
  28522. }
  28523. }
  28524. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28525. continue;
  28526. }
  28527. var world = mesh.getWorldMatrix();
  28528. var ray = rayFunction(world);
  28529. var result = mesh.intersects(ray, fastCheck);
  28530. if (!result || !result.hit)
  28531. continue;
  28532. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28533. continue;
  28534. pickingInfo = result;
  28535. if (fastCheck) {
  28536. break;
  28537. }
  28538. }
  28539. return pickingInfo || new BABYLON.PickingInfo();
  28540. };
  28541. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28542. if (!BABYLON.PickingInfo) {
  28543. return null;
  28544. }
  28545. var pickingInfos = new Array();
  28546. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28547. var mesh = this.meshes[meshIndex];
  28548. if (predicate) {
  28549. if (!predicate(mesh)) {
  28550. continue;
  28551. }
  28552. }
  28553. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28554. continue;
  28555. }
  28556. var world = mesh.getWorldMatrix();
  28557. var ray = rayFunction(world);
  28558. var result = mesh.intersects(ray, false);
  28559. if (!result || !result.hit)
  28560. continue;
  28561. pickingInfos.push(result);
  28562. }
  28563. return pickingInfos;
  28564. };
  28565. /** Launch a ray to try to pick a mesh in the scene
  28566. * @param x position on screen
  28567. * @param y position on screen
  28568. * @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
  28569. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28570. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28571. * @returns a PickingInfo
  28572. */
  28573. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28574. var _this = this;
  28575. if (!BABYLON.PickingInfo) {
  28576. return null;
  28577. }
  28578. var result = this._internalPick(function (world) {
  28579. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28580. return _this._tempPickingRay;
  28581. }, predicate, fastCheck);
  28582. if (result) {
  28583. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28584. }
  28585. return result;
  28586. };
  28587. /** Use the given ray to pick a mesh in the scene
  28588. * @param ray The ray to use to pick meshes
  28589. * @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
  28590. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28591. * @returns a PickingInfo
  28592. */
  28593. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28594. var _this = this;
  28595. var result = this._internalPick(function (world) {
  28596. if (!_this._pickWithRayInverseMatrix) {
  28597. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28598. }
  28599. world.invertToRef(_this._pickWithRayInverseMatrix);
  28600. if (!_this._cachedRayForTransform) {
  28601. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28602. }
  28603. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28604. return _this._cachedRayForTransform;
  28605. }, predicate, fastCheck);
  28606. if (result) {
  28607. result.ray = ray;
  28608. }
  28609. return result;
  28610. };
  28611. /**
  28612. * Launch a ray to try to pick a mesh in the scene
  28613. * @param x X position on screen
  28614. * @param y Y position on screen
  28615. * @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
  28616. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28617. * @returns an array of PickingInfo
  28618. */
  28619. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28620. var _this = this;
  28621. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28622. };
  28623. /**
  28624. * Launch a ray to try to pick a mesh in the scene
  28625. * @param ray Ray to use
  28626. * @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
  28627. * @returns an array of PickingInfo
  28628. */
  28629. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28630. var _this = this;
  28631. return this._internalMultiPick(function (world) {
  28632. if (!_this._pickWithRayInverseMatrix) {
  28633. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28634. }
  28635. world.invertToRef(_this._pickWithRayInverseMatrix);
  28636. if (!_this._cachedRayForTransform) {
  28637. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28638. }
  28639. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28640. return _this._cachedRayForTransform;
  28641. }, predicate);
  28642. };
  28643. /**
  28644. * Force the value of meshUnderPointer
  28645. * @param mesh defines the mesh to use
  28646. */
  28647. Scene.prototype.setPointerOverMesh = function (mesh) {
  28648. if (this._pointerOverMesh === mesh) {
  28649. return;
  28650. }
  28651. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28652. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28653. }
  28654. this._pointerOverMesh = mesh;
  28655. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28656. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28657. }
  28658. };
  28659. /**
  28660. * Gets the mesh under the pointer
  28661. * @returns a Mesh or null if no mesh is under the pointer
  28662. */
  28663. Scene.prototype.getPointerOverMesh = function () {
  28664. return this._pointerOverMesh;
  28665. };
  28666. // Misc.
  28667. /** @hidden */
  28668. Scene.prototype._rebuildGeometries = function () {
  28669. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28670. var geometry = _a[_i];
  28671. geometry._rebuild();
  28672. }
  28673. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28674. var mesh = _c[_b];
  28675. mesh._rebuild();
  28676. }
  28677. if (this.postProcessManager) {
  28678. this.postProcessManager._rebuild();
  28679. }
  28680. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28681. var component = _e[_d];
  28682. component.rebuild();
  28683. }
  28684. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28685. var system = _g[_f];
  28686. system.rebuild();
  28687. }
  28688. };
  28689. /** @hidden */
  28690. Scene.prototype._rebuildTextures = function () {
  28691. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28692. var texture = _a[_i];
  28693. texture._rebuild();
  28694. }
  28695. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28696. };
  28697. // Tags
  28698. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28699. if (tagsQuery === undefined) {
  28700. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28701. return list;
  28702. }
  28703. var listByTags = [];
  28704. forEach = forEach || (function (item) { return; });
  28705. for (var i in list) {
  28706. var item = list[i];
  28707. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28708. listByTags.push(item);
  28709. forEach(item);
  28710. }
  28711. }
  28712. return listByTags;
  28713. };
  28714. /**
  28715. * Get a list of meshes by tags
  28716. * @param tagsQuery defines the tags query to use
  28717. * @param forEach defines a predicate used to filter results
  28718. * @returns an array of Mesh
  28719. */
  28720. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28721. return this._getByTags(this.meshes, tagsQuery, forEach);
  28722. };
  28723. /**
  28724. * Get a list of cameras by tags
  28725. * @param tagsQuery defines the tags query to use
  28726. * @param forEach defines a predicate used to filter results
  28727. * @returns an array of Camera
  28728. */
  28729. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28730. return this._getByTags(this.cameras, tagsQuery, forEach);
  28731. };
  28732. /**
  28733. * Get a list of lights by tags
  28734. * @param tagsQuery defines the tags query to use
  28735. * @param forEach defines a predicate used to filter results
  28736. * @returns an array of Light
  28737. */
  28738. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28739. return this._getByTags(this.lights, tagsQuery, forEach);
  28740. };
  28741. /**
  28742. * Get a list of materials by tags
  28743. * @param tagsQuery defines the tags query to use
  28744. * @param forEach defines a predicate used to filter results
  28745. * @returns an array of Material
  28746. */
  28747. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28748. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28749. };
  28750. /**
  28751. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28752. * This allowed control for front to back rendering or reversly depending of the special needs.
  28753. *
  28754. * @param renderingGroupId The rendering group id corresponding to its index
  28755. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28756. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28757. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28758. */
  28759. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28760. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28761. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28762. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28763. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28764. };
  28765. /**
  28766. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28767. *
  28768. * @param renderingGroupId The rendering group id corresponding to its index
  28769. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28770. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28771. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28772. */
  28773. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28774. if (depth === void 0) { depth = true; }
  28775. if (stencil === void 0) { stencil = true; }
  28776. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28777. };
  28778. /**
  28779. * Gets the current auto clear configuration for one rendering group of the rendering
  28780. * manager.
  28781. * @param index the rendering group index to get the information for
  28782. * @returns The auto clear setup for the requested rendering group
  28783. */
  28784. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28785. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28786. };
  28787. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  28788. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  28789. get: function () {
  28790. return this._blockMaterialDirtyMechanism;
  28791. },
  28792. set: function (value) {
  28793. if (this._blockMaterialDirtyMechanism === value) {
  28794. return;
  28795. }
  28796. this._blockMaterialDirtyMechanism = value;
  28797. if (!value) { // Do a complete update
  28798. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  28799. }
  28800. },
  28801. enumerable: true,
  28802. configurable: true
  28803. });
  28804. /**
  28805. * Will flag all materials as dirty to trigger new shader compilation
  28806. * @param flag defines the flag used to specify which material part must be marked as dirty
  28807. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28808. */
  28809. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28810. if (this._blockMaterialDirtyMechanism) {
  28811. return;
  28812. }
  28813. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28814. var material = _a[_i];
  28815. if (predicate && !predicate(material)) {
  28816. continue;
  28817. }
  28818. material.markAsDirty(flag);
  28819. }
  28820. };
  28821. /** @hidden */
  28822. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28823. var _this = this;
  28824. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28825. this._activeRequests.push(request);
  28826. request.onCompleteObservable.add(function (request) {
  28827. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28828. });
  28829. return request;
  28830. };
  28831. /** @hidden */
  28832. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28833. var _this = this;
  28834. return new Promise(function (resolve, reject) {
  28835. _this._loadFile(url, function (data) {
  28836. resolve(data);
  28837. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28838. reject(exception);
  28839. });
  28840. });
  28841. };
  28842. // Statics
  28843. Scene._uniqueIdCounter = 0;
  28844. /** The fog is deactivated */
  28845. Scene.FOGMODE_NONE = 0;
  28846. /** The fog density is following an exponential function */
  28847. Scene.FOGMODE_EXP = 1;
  28848. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28849. Scene.FOGMODE_EXP2 = 2;
  28850. /** The fog density is following a linear function. */
  28851. Scene.FOGMODE_LINEAR = 3;
  28852. /**
  28853. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28854. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28855. */
  28856. Scene.MinDeltaTime = 1.0;
  28857. /**
  28858. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28859. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28860. */
  28861. Scene.MaxDeltaTime = 1000.0;
  28862. /** The distance in pixel that you have to move to prevent some events */
  28863. Scene.DragMovementThreshold = 10; // in pixels
  28864. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28865. Scene.LongPressDelay = 500; // in milliseconds
  28866. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28867. Scene.DoubleClickDelay = 300; // in milliseconds
  28868. /** If you need to check double click without raising a single click at first click, enable this flag */
  28869. Scene.ExclusiveDoubleClickMode = false;
  28870. return Scene;
  28871. }(BABYLON.AbstractScene));
  28872. BABYLON.Scene = Scene;
  28873. })(BABYLON || (BABYLON = {}));
  28874. //# sourceMappingURL=babylon.scene.js.map
  28875. var BABYLON;
  28876. (function (BABYLON) {
  28877. /**
  28878. * Set of assets to keep when moving a scene into an asset container.
  28879. */
  28880. var KeepAssets = /** @class */ (function (_super) {
  28881. __extends(KeepAssets, _super);
  28882. function KeepAssets() {
  28883. return _super !== null && _super.apply(this, arguments) || this;
  28884. }
  28885. return KeepAssets;
  28886. }(BABYLON.AbstractScene));
  28887. BABYLON.KeepAssets = KeepAssets;
  28888. /**
  28889. * Container with a set of assets that can be added or removed from a scene.
  28890. */
  28891. var AssetContainer = /** @class */ (function (_super) {
  28892. __extends(AssetContainer, _super);
  28893. /**
  28894. * Instantiates an AssetContainer.
  28895. * @param scene The scene the AssetContainer belongs to.
  28896. */
  28897. function AssetContainer(scene) {
  28898. var _this = _super.call(this) || this;
  28899. _this.scene = scene;
  28900. return _this;
  28901. }
  28902. /**
  28903. * Adds all the assets from the container to the scene.
  28904. */
  28905. AssetContainer.prototype.addAllToScene = function () {
  28906. var _this = this;
  28907. this.cameras.forEach(function (o) {
  28908. _this.scene.addCamera(o);
  28909. });
  28910. this.lights.forEach(function (o) {
  28911. _this.scene.addLight(o);
  28912. });
  28913. this.meshes.forEach(function (o) {
  28914. _this.scene.addMesh(o);
  28915. });
  28916. this.skeletons.forEach(function (o) {
  28917. _this.scene.addSkeleton(o);
  28918. });
  28919. this.animations.forEach(function (o) {
  28920. _this.scene.addAnimation(o);
  28921. });
  28922. this.animationGroups.forEach(function (o) {
  28923. _this.scene.addAnimationGroup(o);
  28924. });
  28925. this.multiMaterials.forEach(function (o) {
  28926. _this.scene.addMultiMaterial(o);
  28927. });
  28928. this.materials.forEach(function (o) {
  28929. _this.scene.addMaterial(o);
  28930. });
  28931. this.morphTargetManagers.forEach(function (o) {
  28932. _this.scene.addMorphTargetManager(o);
  28933. });
  28934. this.geometries.forEach(function (o) {
  28935. _this.scene.addGeometry(o);
  28936. });
  28937. this.transformNodes.forEach(function (o) {
  28938. _this.scene.addTransformNode(o);
  28939. });
  28940. this.actionManagers.forEach(function (o) {
  28941. _this.scene.addActionManager(o);
  28942. });
  28943. this.textures.forEach(function (o) {
  28944. _this.scene.addTexture(o);
  28945. });
  28946. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28947. var component = _a[_i];
  28948. component.addFromContainer(this.scene);
  28949. }
  28950. };
  28951. /**
  28952. * Removes all the assets in the container from the scene
  28953. */
  28954. AssetContainer.prototype.removeAllFromScene = function () {
  28955. var _this = this;
  28956. this.cameras.forEach(function (o) {
  28957. _this.scene.removeCamera(o);
  28958. });
  28959. this.lights.forEach(function (o) {
  28960. _this.scene.removeLight(o);
  28961. });
  28962. this.meshes.forEach(function (o) {
  28963. _this.scene.removeMesh(o);
  28964. });
  28965. this.skeletons.forEach(function (o) {
  28966. _this.scene.removeSkeleton(o);
  28967. });
  28968. this.animations.forEach(function (o) {
  28969. _this.scene.removeAnimation(o);
  28970. });
  28971. this.animationGroups.forEach(function (o) {
  28972. _this.scene.removeAnimationGroup(o);
  28973. });
  28974. this.multiMaterials.forEach(function (o) {
  28975. _this.scene.removeMultiMaterial(o);
  28976. });
  28977. this.materials.forEach(function (o) {
  28978. _this.scene.removeMaterial(o);
  28979. });
  28980. this.morphTargetManagers.forEach(function (o) {
  28981. _this.scene.removeMorphTargetManager(o);
  28982. });
  28983. this.geometries.forEach(function (o) {
  28984. _this.scene.removeGeometry(o);
  28985. });
  28986. this.transformNodes.forEach(function (o) {
  28987. _this.scene.removeTransformNode(o);
  28988. });
  28989. this.actionManagers.forEach(function (o) {
  28990. _this.scene.removeActionManager(o);
  28991. });
  28992. this.textures.forEach(function (o) {
  28993. _this.scene.removeTexture(o);
  28994. });
  28995. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28996. var component = _a[_i];
  28997. component.removeFromContainer(this.scene);
  28998. }
  28999. };
  29000. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29001. if (!sourceAssets) {
  29002. return;
  29003. }
  29004. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29005. var asset = sourceAssets_1[_i];
  29006. var move = true;
  29007. if (keepAssets) {
  29008. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29009. var keepAsset = keepAssets_1[_a];
  29010. if (asset === keepAsset) {
  29011. move = false;
  29012. break;
  29013. }
  29014. }
  29015. }
  29016. if (move) {
  29017. targetAssets.push(asset);
  29018. }
  29019. }
  29020. };
  29021. /**
  29022. * Removes all the assets contained in the scene and adds them to the container.
  29023. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29024. */
  29025. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29026. if (keepAssets === undefined) {
  29027. keepAssets = new KeepAssets();
  29028. }
  29029. for (var key in this) {
  29030. if (this.hasOwnProperty(key)) {
  29031. this[key] = this[key] || [];
  29032. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29033. }
  29034. }
  29035. this.removeAllFromScene();
  29036. };
  29037. /**
  29038. * 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.
  29039. * @returns the root mesh
  29040. */
  29041. AssetContainer.prototype.createRootMesh = function () {
  29042. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29043. this.meshes.forEach(function (m) {
  29044. if (!m.parent) {
  29045. rootMesh.addChild(m);
  29046. }
  29047. });
  29048. this.meshes.unshift(rootMesh);
  29049. return rootMesh;
  29050. };
  29051. return AssetContainer;
  29052. }(BABYLON.AbstractScene));
  29053. BABYLON.AssetContainer = AssetContainer;
  29054. })(BABYLON || (BABYLON = {}));
  29055. //# sourceMappingURL=babylon.assetContainer.js.map
  29056. var BABYLON;
  29057. (function (BABYLON) {
  29058. var Buffer = /** @class */ (function () {
  29059. /**
  29060. * Constructor
  29061. * @param engine the engine
  29062. * @param data the data to use for this buffer
  29063. * @param updatable whether the data is updatable
  29064. * @param stride the stride (optional)
  29065. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29066. * @param instanced whether the buffer is instanced (optional)
  29067. * @param useBytes set to true if the stride in in bytes (optional)
  29068. */
  29069. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29070. if (stride === void 0) { stride = 0; }
  29071. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29072. if (instanced === void 0) { instanced = false; }
  29073. if (useBytes === void 0) { useBytes = false; }
  29074. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29075. this._engine = engine.getScene().getEngine();
  29076. }
  29077. else {
  29078. this._engine = engine;
  29079. }
  29080. this._updatable = updatable;
  29081. this._instanced = instanced;
  29082. this._data = data;
  29083. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29084. if (!postponeInternalCreation) { // by default
  29085. this.create();
  29086. }
  29087. }
  29088. /**
  29089. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29090. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29091. * @param offset defines offset in the buffer (0 by default)
  29092. * @param size defines the size in floats of attributes (position is 3 for instance)
  29093. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29094. * @param instanced defines if the vertex buffer contains indexed data
  29095. * @param useBytes defines if the offset and stride are in bytes
  29096. * @returns the new vertex buffer
  29097. */
  29098. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29099. if (useBytes === void 0) { useBytes = false; }
  29100. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29101. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29102. // a lot of these parameters are ignored as they are overriden by the buffer
  29103. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29104. };
  29105. // Properties
  29106. Buffer.prototype.isUpdatable = function () {
  29107. return this._updatable;
  29108. };
  29109. Buffer.prototype.getData = function () {
  29110. return this._data;
  29111. };
  29112. Buffer.prototype.getBuffer = function () {
  29113. return this._buffer;
  29114. };
  29115. /**
  29116. * Gets the stride in float32 units (i.e. byte stride / 4).
  29117. * May not be an integer if the byte stride is not divisible by 4.
  29118. * DEPRECATED. Use byteStride instead.
  29119. * @returns the stride in float32 units
  29120. */
  29121. Buffer.prototype.getStrideSize = function () {
  29122. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29123. };
  29124. // Methods
  29125. Buffer.prototype.create = function (data) {
  29126. if (data === void 0) { data = null; }
  29127. if (!data && this._buffer) {
  29128. return; // nothing to do
  29129. }
  29130. data = data || this._data;
  29131. if (!data) {
  29132. return;
  29133. }
  29134. if (!this._buffer) { // create buffer
  29135. if (this._updatable) {
  29136. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29137. this._data = data;
  29138. }
  29139. else {
  29140. this._buffer = this._engine.createVertexBuffer(data);
  29141. }
  29142. }
  29143. else if (this._updatable) { // update buffer
  29144. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29145. this._data = data;
  29146. }
  29147. };
  29148. /** @hidden */
  29149. Buffer.prototype._rebuild = function () {
  29150. this._buffer = null;
  29151. this.create(this._data);
  29152. };
  29153. Buffer.prototype.update = function (data) {
  29154. this.create(data);
  29155. };
  29156. /**
  29157. * Updates the data directly.
  29158. * @param data the new data
  29159. * @param offset the new offset
  29160. * @param vertexCount the vertex count (optional)
  29161. * @param useBytes set to true if the offset is in bytes
  29162. */
  29163. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29164. if (useBytes === void 0) { useBytes = false; }
  29165. if (!this._buffer) {
  29166. return;
  29167. }
  29168. if (this._updatable) { // update buffer
  29169. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29170. this._data = null;
  29171. }
  29172. };
  29173. Buffer.prototype.dispose = function () {
  29174. if (!this._buffer) {
  29175. return;
  29176. }
  29177. if (this._engine._releaseBuffer(this._buffer)) {
  29178. this._buffer = null;
  29179. }
  29180. };
  29181. return Buffer;
  29182. }());
  29183. BABYLON.Buffer = Buffer;
  29184. })(BABYLON || (BABYLON = {}));
  29185. //# sourceMappingURL=babylon.buffer.js.map
  29186. var BABYLON;
  29187. (function (BABYLON) {
  29188. var VertexBuffer = /** @class */ (function () {
  29189. /**
  29190. * Constructor
  29191. * @param engine the engine
  29192. * @param data the data to use for this vertex buffer
  29193. * @param kind the vertex buffer kind
  29194. * @param updatable whether the data is updatable
  29195. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29196. * @param stride the stride (optional)
  29197. * @param instanced whether the buffer is instanced (optional)
  29198. * @param offset the offset of the data (optional)
  29199. * @param size the number of components (optional)
  29200. * @param type the type of the component (optional)
  29201. * @param normalized whether the data contains normalized data (optional)
  29202. * @param useBytes set to true if stride and offset are in bytes (optional)
  29203. */
  29204. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29205. if (normalized === void 0) { normalized = false; }
  29206. if (useBytes === void 0) { useBytes = false; }
  29207. if (data instanceof BABYLON.Buffer) {
  29208. this._buffer = data;
  29209. this._ownsBuffer = false;
  29210. }
  29211. else {
  29212. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29213. this._ownsBuffer = true;
  29214. }
  29215. this._kind = kind;
  29216. if (type == undefined) {
  29217. var data_1 = this.getData();
  29218. this.type = VertexBuffer.FLOAT;
  29219. if (data_1 instanceof Int8Array)
  29220. this.type = VertexBuffer.BYTE;
  29221. else if (data_1 instanceof Uint8Array)
  29222. this.type = VertexBuffer.UNSIGNED_BYTE;
  29223. else if (data_1 instanceof Int16Array)
  29224. this.type = VertexBuffer.SHORT;
  29225. else if (data_1 instanceof Uint16Array)
  29226. this.type = VertexBuffer.UNSIGNED_SHORT;
  29227. else if (data_1 instanceof Int32Array)
  29228. this.type = VertexBuffer.INT;
  29229. else if (data_1 instanceof Uint32Array)
  29230. this.type = VertexBuffer.UNSIGNED_INT;
  29231. }
  29232. else {
  29233. this.type = type;
  29234. }
  29235. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29236. if (useBytes) {
  29237. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29238. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29239. this.byteOffset = offset || 0;
  29240. }
  29241. else {
  29242. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29243. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29244. this.byteOffset = (offset || 0) * typeByteLength;
  29245. }
  29246. this.normalized = normalized;
  29247. this._instanced = instanced !== undefined ? instanced : false;
  29248. this._instanceDivisor = instanced ? 1 : 0;
  29249. }
  29250. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29251. /**
  29252. * Gets or sets the instance divisor when in instanced mode
  29253. */
  29254. get: function () {
  29255. return this._instanceDivisor;
  29256. },
  29257. set: function (value) {
  29258. this._instanceDivisor = value;
  29259. if (value == 0) {
  29260. this._instanced = false;
  29261. }
  29262. else {
  29263. this._instanced = true;
  29264. }
  29265. },
  29266. enumerable: true,
  29267. configurable: true
  29268. });
  29269. /** @hidden */
  29270. VertexBuffer.prototype._rebuild = function () {
  29271. if (!this._buffer) {
  29272. return;
  29273. }
  29274. this._buffer._rebuild();
  29275. };
  29276. /**
  29277. * Returns the kind of the VertexBuffer (string).
  29278. */
  29279. VertexBuffer.prototype.getKind = function () {
  29280. return this._kind;
  29281. };
  29282. // Properties
  29283. /**
  29284. * Boolean : is the VertexBuffer updatable ?
  29285. */
  29286. VertexBuffer.prototype.isUpdatable = function () {
  29287. return this._buffer.isUpdatable();
  29288. };
  29289. /**
  29290. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29291. */
  29292. VertexBuffer.prototype.getData = function () {
  29293. return this._buffer.getData();
  29294. };
  29295. /**
  29296. * Returns the WebGLBuffer associated to the VertexBuffer.
  29297. */
  29298. VertexBuffer.prototype.getBuffer = function () {
  29299. return this._buffer.getBuffer();
  29300. };
  29301. /**
  29302. * Returns the stride as a multiple of the type byte length.
  29303. * DEPRECATED. Use byteStride instead.
  29304. */
  29305. VertexBuffer.prototype.getStrideSize = function () {
  29306. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29307. };
  29308. /**
  29309. * Returns the offset as a multiple of the type byte length.
  29310. * DEPRECATED. Use byteOffset instead.
  29311. */
  29312. VertexBuffer.prototype.getOffset = function () {
  29313. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29314. };
  29315. /**
  29316. * Returns the number of components per vertex attribute (integer).
  29317. */
  29318. VertexBuffer.prototype.getSize = function () {
  29319. return this._size;
  29320. };
  29321. /**
  29322. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29323. */
  29324. VertexBuffer.prototype.getIsInstanced = function () {
  29325. return this._instanced;
  29326. };
  29327. /**
  29328. * Returns the instancing divisor, zero for non-instanced (integer).
  29329. */
  29330. VertexBuffer.prototype.getInstanceDivisor = function () {
  29331. return this._instanceDivisor;
  29332. };
  29333. // Methods
  29334. /**
  29335. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29336. * Returns the created WebGLBuffer.
  29337. */
  29338. VertexBuffer.prototype.create = function (data) {
  29339. return this._buffer.create(data);
  29340. };
  29341. /**
  29342. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29343. * This function will create a new buffer if the current one is not updatable
  29344. * Returns the updated WebGLBuffer.
  29345. */
  29346. VertexBuffer.prototype.update = function (data) {
  29347. return this._buffer.update(data);
  29348. };
  29349. /**
  29350. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29351. * Returns the directly updated WebGLBuffer.
  29352. * @param data the new data
  29353. * @param offset the new offset
  29354. * @param useBytes set to true if the offset is in bytes
  29355. */
  29356. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29357. if (useBytes === void 0) { useBytes = false; }
  29358. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29359. };
  29360. /**
  29361. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29362. */
  29363. VertexBuffer.prototype.dispose = function () {
  29364. if (this._ownsBuffer) {
  29365. this._buffer.dispose();
  29366. }
  29367. };
  29368. /**
  29369. * Enumerates each value of this vertex buffer as numbers.
  29370. * @param count the number of values to enumerate
  29371. * @param callback the callback function called for each value
  29372. */
  29373. VertexBuffer.prototype.forEach = function (count, callback) {
  29374. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29375. };
  29376. Object.defineProperty(VertexBuffer, "PositionKind", {
  29377. get: function () {
  29378. return VertexBuffer._PositionKind;
  29379. },
  29380. enumerable: true,
  29381. configurable: true
  29382. });
  29383. Object.defineProperty(VertexBuffer, "NormalKind", {
  29384. get: function () {
  29385. return VertexBuffer._NormalKind;
  29386. },
  29387. enumerable: true,
  29388. configurable: true
  29389. });
  29390. Object.defineProperty(VertexBuffer, "TangentKind", {
  29391. get: function () {
  29392. return VertexBuffer._TangentKind;
  29393. },
  29394. enumerable: true,
  29395. configurable: true
  29396. });
  29397. Object.defineProperty(VertexBuffer, "UVKind", {
  29398. get: function () {
  29399. return VertexBuffer._UVKind;
  29400. },
  29401. enumerable: true,
  29402. configurable: true
  29403. });
  29404. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29405. get: function () {
  29406. return VertexBuffer._UV2Kind;
  29407. },
  29408. enumerable: true,
  29409. configurable: true
  29410. });
  29411. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29412. get: function () {
  29413. return VertexBuffer._UV3Kind;
  29414. },
  29415. enumerable: true,
  29416. configurable: true
  29417. });
  29418. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29419. get: function () {
  29420. return VertexBuffer._UV4Kind;
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29426. get: function () {
  29427. return VertexBuffer._UV5Kind;
  29428. },
  29429. enumerable: true,
  29430. configurable: true
  29431. });
  29432. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29433. get: function () {
  29434. return VertexBuffer._UV6Kind;
  29435. },
  29436. enumerable: true,
  29437. configurable: true
  29438. });
  29439. Object.defineProperty(VertexBuffer, "ColorKind", {
  29440. get: function () {
  29441. return VertexBuffer._ColorKind;
  29442. },
  29443. enumerable: true,
  29444. configurable: true
  29445. });
  29446. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29447. get: function () {
  29448. return VertexBuffer._MatricesIndicesKind;
  29449. },
  29450. enumerable: true,
  29451. configurable: true
  29452. });
  29453. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29454. get: function () {
  29455. return VertexBuffer._MatricesWeightsKind;
  29456. },
  29457. enumerable: true,
  29458. configurable: true
  29459. });
  29460. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29461. get: function () {
  29462. return VertexBuffer._MatricesIndicesExtraKind;
  29463. },
  29464. enumerable: true,
  29465. configurable: true
  29466. });
  29467. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29468. get: function () {
  29469. return VertexBuffer._MatricesWeightsExtraKind;
  29470. },
  29471. enumerable: true,
  29472. configurable: true
  29473. });
  29474. /**
  29475. * Deduces the stride given a kind.
  29476. * @param kind The kind string to deduce
  29477. * @returns The deduced stride
  29478. */
  29479. VertexBuffer.DeduceStride = function (kind) {
  29480. switch (kind) {
  29481. case VertexBuffer.UVKind:
  29482. case VertexBuffer.UV2Kind:
  29483. case VertexBuffer.UV3Kind:
  29484. case VertexBuffer.UV4Kind:
  29485. case VertexBuffer.UV5Kind:
  29486. case VertexBuffer.UV6Kind:
  29487. return 2;
  29488. case VertexBuffer.NormalKind:
  29489. case VertexBuffer.PositionKind:
  29490. return 3;
  29491. case VertexBuffer.ColorKind:
  29492. case VertexBuffer.MatricesIndicesKind:
  29493. case VertexBuffer.MatricesIndicesExtraKind:
  29494. case VertexBuffer.MatricesWeightsKind:
  29495. case VertexBuffer.MatricesWeightsExtraKind:
  29496. case VertexBuffer.TangentKind:
  29497. return 4;
  29498. default:
  29499. throw new Error("Invalid kind '" + kind + "'");
  29500. }
  29501. };
  29502. /**
  29503. * Gets the byte length of the given type.
  29504. * @param type the type
  29505. * @returns the number of bytes
  29506. */
  29507. VertexBuffer.GetTypeByteLength = function (type) {
  29508. switch (type) {
  29509. case VertexBuffer.BYTE:
  29510. case VertexBuffer.UNSIGNED_BYTE:
  29511. return 1;
  29512. case VertexBuffer.SHORT:
  29513. case VertexBuffer.UNSIGNED_SHORT:
  29514. return 2;
  29515. case VertexBuffer.INT:
  29516. case VertexBuffer.FLOAT:
  29517. return 4;
  29518. default:
  29519. throw new Error("Invalid type '" + type + "'");
  29520. }
  29521. };
  29522. /**
  29523. * Enumerates each value of the given parameters as numbers.
  29524. * @param data the data to enumerate
  29525. * @param byteOffset the byte offset of the data
  29526. * @param byteStride the byte stride of the data
  29527. * @param componentCount the number of components per element
  29528. * @param componentType the type of the component
  29529. * @param count the total number of components
  29530. * @param normalized whether the data is normalized
  29531. * @param callback the callback function called for each value
  29532. */
  29533. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29534. if (data instanceof Array) {
  29535. var offset = byteOffset / 4;
  29536. var stride = byteStride / 4;
  29537. for (var index = 0; index < count; index += componentCount) {
  29538. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29539. callback(data[offset + componentIndex], index + componentIndex);
  29540. }
  29541. offset += stride;
  29542. }
  29543. }
  29544. else {
  29545. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29546. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29547. for (var index = 0; index < count; index += componentCount) {
  29548. var componentByteOffset = byteOffset;
  29549. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29550. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29551. callback(value, index + componentIndex);
  29552. componentByteOffset += componentByteLength;
  29553. }
  29554. byteOffset += byteStride;
  29555. }
  29556. }
  29557. };
  29558. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29559. switch (type) {
  29560. case VertexBuffer.BYTE: {
  29561. var value = dataView.getInt8(byteOffset);
  29562. if (normalized) {
  29563. value = Math.max(value / 127, -1);
  29564. }
  29565. return value;
  29566. }
  29567. case VertexBuffer.UNSIGNED_BYTE: {
  29568. var value = dataView.getUint8(byteOffset);
  29569. if (normalized) {
  29570. value = value / 255;
  29571. }
  29572. return value;
  29573. }
  29574. case VertexBuffer.SHORT: {
  29575. var value = dataView.getInt16(byteOffset, true);
  29576. if (normalized) {
  29577. value = Math.max(value / 16383, -1);
  29578. }
  29579. return value;
  29580. }
  29581. case VertexBuffer.UNSIGNED_SHORT: {
  29582. var value = dataView.getUint16(byteOffset, true);
  29583. if (normalized) {
  29584. value = value / 65535;
  29585. }
  29586. return value;
  29587. }
  29588. case VertexBuffer.FLOAT: {
  29589. return dataView.getFloat32(byteOffset, true);
  29590. }
  29591. default: {
  29592. throw new Error("Invalid component type " + type);
  29593. }
  29594. }
  29595. };
  29596. /**
  29597. * The byte type.
  29598. */
  29599. VertexBuffer.BYTE = 5120;
  29600. /**
  29601. * The unsigned byte type.
  29602. */
  29603. VertexBuffer.UNSIGNED_BYTE = 5121;
  29604. /**
  29605. * The short type.
  29606. */
  29607. VertexBuffer.SHORT = 5122;
  29608. /**
  29609. * The unsigned short type.
  29610. */
  29611. VertexBuffer.UNSIGNED_SHORT = 5123;
  29612. /**
  29613. * The integer type.
  29614. */
  29615. VertexBuffer.INT = 5124;
  29616. /**
  29617. * The unsigned integer type.
  29618. */
  29619. VertexBuffer.UNSIGNED_INT = 5125;
  29620. /**
  29621. * The float type.
  29622. */
  29623. VertexBuffer.FLOAT = 5126;
  29624. // Enums
  29625. VertexBuffer._PositionKind = "position";
  29626. VertexBuffer._NormalKind = "normal";
  29627. VertexBuffer._TangentKind = "tangent";
  29628. VertexBuffer._UVKind = "uv";
  29629. VertexBuffer._UV2Kind = "uv2";
  29630. VertexBuffer._UV3Kind = "uv3";
  29631. VertexBuffer._UV4Kind = "uv4";
  29632. VertexBuffer._UV5Kind = "uv5";
  29633. VertexBuffer._UV6Kind = "uv6";
  29634. VertexBuffer._ColorKind = "color";
  29635. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29636. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29637. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29638. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29639. return VertexBuffer;
  29640. }());
  29641. BABYLON.VertexBuffer = VertexBuffer;
  29642. })(BABYLON || (BABYLON = {}));
  29643. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29644. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29645. var BABYLON;
  29646. (function (BABYLON) {
  29647. /**
  29648. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29649. */
  29650. var DummyInternalTextureTracker = /** @class */ (function () {
  29651. function DummyInternalTextureTracker() {
  29652. /**
  29653. * Gets or set the previous tracker in the list
  29654. */
  29655. this.previous = null;
  29656. /**
  29657. * Gets or set the next tracker in the list
  29658. */
  29659. this.next = null;
  29660. }
  29661. return DummyInternalTextureTracker;
  29662. }());
  29663. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29664. })(BABYLON || (BABYLON = {}));
  29665. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29666. var BABYLON;
  29667. (function (BABYLON) {
  29668. /**
  29669. * Class used to store data associated with WebGL texture data for the engine
  29670. * This class should not be used directly
  29671. */
  29672. var InternalTexture = /** @class */ (function () {
  29673. /**
  29674. * Creates a new InternalTexture
  29675. * @param engine defines the engine to use
  29676. * @param dataSource defines the type of data that will be used
  29677. */
  29678. function InternalTexture(engine, dataSource) {
  29679. /**
  29680. * Observable called when the texture is loaded
  29681. */
  29682. this.onLoadedObservable = new BABYLON.Observable();
  29683. /**
  29684. * Gets or set the previous tracker in the list
  29685. */
  29686. this.previous = null;
  29687. /**
  29688. * Gets or set the next tracker in the list
  29689. */
  29690. this.next = null;
  29691. // Private
  29692. /** @hidden */
  29693. this._initialSlot = -1;
  29694. /** @hidden */
  29695. this._designatedSlot = -1;
  29696. /** @hidden */
  29697. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29698. /** @hidden */
  29699. this._comparisonFunction = 0;
  29700. /** @hidden */
  29701. this._sphericalPolynomial = null;
  29702. /** @hidden */
  29703. this._lodGenerationScale = 0;
  29704. /** @hidden */
  29705. this._lodGenerationOffset = 0;
  29706. /** @hidden */
  29707. this._isRGBD = false;
  29708. /** @hidden */
  29709. this._references = 1;
  29710. this._engine = engine;
  29711. this._dataSource = dataSource;
  29712. this._webGLTexture = engine._createTexture();
  29713. }
  29714. /**
  29715. * Gets the Engine the texture belongs to.
  29716. * @returns The babylon engine
  29717. */
  29718. InternalTexture.prototype.getEngine = function () {
  29719. return this._engine;
  29720. };
  29721. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29722. /**
  29723. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29724. */
  29725. get: function () {
  29726. return this._dataSource;
  29727. },
  29728. enumerable: true,
  29729. configurable: true
  29730. });
  29731. /**
  29732. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29733. */
  29734. InternalTexture.prototype.incrementReferences = function () {
  29735. this._references++;
  29736. };
  29737. /**
  29738. * Change the size of the texture (not the size of the content)
  29739. * @param width defines the new width
  29740. * @param height defines the new height
  29741. * @param depth defines the new depth (1 by default)
  29742. */
  29743. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29744. if (depth === void 0) { depth = 1; }
  29745. this.width = width;
  29746. this.height = height;
  29747. this.depth = depth;
  29748. this.baseWidth = width;
  29749. this.baseHeight = height;
  29750. this.baseDepth = depth;
  29751. this._size = width * height * depth;
  29752. };
  29753. /** @hidden */
  29754. InternalTexture.prototype._rebuild = function () {
  29755. var _this = this;
  29756. var proxy;
  29757. this.isReady = false;
  29758. this._cachedCoordinatesMode = null;
  29759. this._cachedWrapU = null;
  29760. this._cachedWrapV = null;
  29761. this._cachedAnisotropicFilteringLevel = null;
  29762. switch (this._dataSource) {
  29763. case InternalTexture.DATASOURCE_TEMP:
  29764. return;
  29765. case InternalTexture.DATASOURCE_URL:
  29766. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29767. _this.isReady = true;
  29768. }, null, this._buffer, undefined, this.format);
  29769. proxy._swapAndDie(this);
  29770. return;
  29771. case InternalTexture.DATASOURCE_RAW:
  29772. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29773. proxy._swapAndDie(this);
  29774. this.isReady = true;
  29775. return;
  29776. case InternalTexture.DATASOURCE_RAW3D:
  29777. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29778. proxy._swapAndDie(this);
  29779. this.isReady = true;
  29780. return;
  29781. case InternalTexture.DATASOURCE_DYNAMIC:
  29782. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29783. proxy._swapAndDie(this);
  29784. // The engine will make sure to update content so no need to flag it as isReady = true
  29785. return;
  29786. case InternalTexture.DATASOURCE_RENDERTARGET:
  29787. var options = new BABYLON.RenderTargetCreationOptions();
  29788. options.generateDepthBuffer = this._generateDepthBuffer;
  29789. options.generateMipMaps = this.generateMipMaps;
  29790. options.generateStencilBuffer = this._generateStencilBuffer;
  29791. options.samplingMode = this.samplingMode;
  29792. options.type = this.type;
  29793. if (this.isCube) {
  29794. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29795. }
  29796. else {
  29797. var size = {
  29798. width: this.width,
  29799. height: this.height
  29800. };
  29801. proxy = this._engine.createRenderTargetTexture(size, options);
  29802. }
  29803. proxy._swapAndDie(this);
  29804. this.isReady = true;
  29805. return;
  29806. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29807. var depthTextureOptions = {
  29808. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29809. comparisonFunction: this._comparisonFunction,
  29810. generateStencil: this._generateStencilBuffer,
  29811. isCube: this.isCube
  29812. };
  29813. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29814. proxy._swapAndDie(this);
  29815. this.isReady = true;
  29816. return;
  29817. case InternalTexture.DATASOURCE_CUBE:
  29818. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29819. _this.isReady = true;
  29820. }, null, this.format, this._extension);
  29821. proxy._swapAndDie(this);
  29822. return;
  29823. case InternalTexture.DATASOURCE_CUBERAW:
  29824. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29825. proxy._swapAndDie(this);
  29826. this.isReady = true;
  29827. return;
  29828. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29829. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29830. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29831. _this.isReady = true;
  29832. });
  29833. proxy._swapAndDie(this);
  29834. return;
  29835. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29836. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29837. if (proxy) {
  29838. proxy._swapAndDie(_this);
  29839. }
  29840. _this.isReady = true;
  29841. }, null, this.format, this._extension);
  29842. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29843. return;
  29844. }
  29845. };
  29846. /** @hidden */
  29847. InternalTexture.prototype._swapAndDie = function (target) {
  29848. target._webGLTexture = this._webGLTexture;
  29849. if (this._framebuffer) {
  29850. target._framebuffer = this._framebuffer;
  29851. }
  29852. if (this._depthStencilBuffer) {
  29853. target._depthStencilBuffer = this._depthStencilBuffer;
  29854. }
  29855. if (this._lodTextureHigh) {
  29856. if (target._lodTextureHigh) {
  29857. target._lodTextureHigh.dispose();
  29858. }
  29859. target._lodTextureHigh = this._lodTextureHigh;
  29860. }
  29861. if (this._lodTextureMid) {
  29862. if (target._lodTextureMid) {
  29863. target._lodTextureMid.dispose();
  29864. }
  29865. target._lodTextureMid = this._lodTextureMid;
  29866. }
  29867. if (this._lodTextureLow) {
  29868. if (target._lodTextureLow) {
  29869. target._lodTextureLow.dispose();
  29870. }
  29871. target._lodTextureLow = this._lodTextureLow;
  29872. }
  29873. var cache = this._engine.getLoadedTexturesCache();
  29874. var index = cache.indexOf(this);
  29875. if (index !== -1) {
  29876. cache.splice(index, 1);
  29877. }
  29878. };
  29879. /**
  29880. * Dispose the current allocated resources
  29881. */
  29882. InternalTexture.prototype.dispose = function () {
  29883. if (!this._webGLTexture) {
  29884. return;
  29885. }
  29886. this._references--;
  29887. if (this._references === 0) {
  29888. this._engine._releaseTexture(this);
  29889. this._webGLTexture = null;
  29890. this.previous = null;
  29891. this.next = null;
  29892. }
  29893. };
  29894. /**
  29895. * The source of the texture data is unknown
  29896. */
  29897. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29898. /**
  29899. * Texture data comes from an URL
  29900. */
  29901. InternalTexture.DATASOURCE_URL = 1;
  29902. /**
  29903. * Texture data is only used for temporary storage
  29904. */
  29905. InternalTexture.DATASOURCE_TEMP = 2;
  29906. /**
  29907. * Texture data comes from raw data (ArrayBuffer)
  29908. */
  29909. InternalTexture.DATASOURCE_RAW = 3;
  29910. /**
  29911. * Texture content is dynamic (video or dynamic texture)
  29912. */
  29913. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29914. /**
  29915. * Texture content is generated by rendering to it
  29916. */
  29917. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29918. /**
  29919. * Texture content is part of a multi render target process
  29920. */
  29921. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29922. /**
  29923. * Texture data comes from a cube data file
  29924. */
  29925. InternalTexture.DATASOURCE_CUBE = 7;
  29926. /**
  29927. * Texture data comes from a raw cube data
  29928. */
  29929. InternalTexture.DATASOURCE_CUBERAW = 8;
  29930. /**
  29931. * Texture data come from a prefiltered cube data file
  29932. */
  29933. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29934. /**
  29935. * Texture content is raw 3D data
  29936. */
  29937. InternalTexture.DATASOURCE_RAW3D = 10;
  29938. /**
  29939. * Texture content is a depth texture
  29940. */
  29941. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29942. /**
  29943. * Texture data comes from a raw cube data encoded with RGBD
  29944. */
  29945. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29946. return InternalTexture;
  29947. }());
  29948. BABYLON.InternalTexture = InternalTexture;
  29949. })(BABYLON || (BABYLON = {}));
  29950. //# sourceMappingURL=babylon.internalTexture.js.map
  29951. var BABYLON;
  29952. (function (BABYLON) {
  29953. var BaseTexture = /** @class */ (function () {
  29954. function BaseTexture(scene) {
  29955. this._hasAlpha = false;
  29956. this.getAlphaFromRGB = false;
  29957. this.level = 1;
  29958. this.coordinatesIndex = 0;
  29959. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29960. /**
  29961. * | Value | Type | Description |
  29962. * | ----- | ------------------ | ----------- |
  29963. * | 0 | CLAMP_ADDRESSMODE | |
  29964. * | 1 | WRAP_ADDRESSMODE | |
  29965. * | 2 | MIRROR_ADDRESSMODE | |
  29966. */
  29967. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29968. /**
  29969. * | Value | Type | Description |
  29970. * | ----- | ------------------ | ----------- |
  29971. * | 0 | CLAMP_ADDRESSMODE | |
  29972. * | 1 | WRAP_ADDRESSMODE | |
  29973. * | 2 | MIRROR_ADDRESSMODE | |
  29974. */
  29975. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29976. /**
  29977. * | Value | Type | Description |
  29978. * | ----- | ------------------ | ----------- |
  29979. * | 0 | CLAMP_ADDRESSMODE | |
  29980. * | 1 | WRAP_ADDRESSMODE | |
  29981. * | 2 | MIRROR_ADDRESSMODE | |
  29982. */
  29983. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29984. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29985. this.isCube = false;
  29986. this.is3D = false;
  29987. this.gammaSpace = true;
  29988. this.invertZ = false;
  29989. this.lodLevelInAlpha = false;
  29990. this.isRenderTarget = false;
  29991. this.animations = new Array();
  29992. /**
  29993. * An event triggered when the texture is disposed.
  29994. */
  29995. this.onDisposeObservable = new BABYLON.Observable();
  29996. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29997. this._cachedSize = BABYLON.Size.Zero();
  29998. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29999. if (this._scene) {
  30000. this._scene.textures.push(this);
  30001. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30002. }
  30003. this._uid = null;
  30004. }
  30005. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30006. get: function () {
  30007. return this._hasAlpha;
  30008. },
  30009. set: function (value) {
  30010. if (this._hasAlpha === value) {
  30011. return;
  30012. }
  30013. this._hasAlpha = value;
  30014. if (this._scene) {
  30015. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30016. }
  30017. },
  30018. enumerable: true,
  30019. configurable: true
  30020. });
  30021. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30022. get: function () {
  30023. return this._coordinatesMode;
  30024. },
  30025. /**
  30026. * How a texture is mapped.
  30027. *
  30028. * | Value | Type | Description |
  30029. * | ----- | ----------------------------------- | ----------- |
  30030. * | 0 | EXPLICIT_MODE | |
  30031. * | 1 | SPHERICAL_MODE | |
  30032. * | 2 | PLANAR_MODE | |
  30033. * | 3 | CUBIC_MODE | |
  30034. * | 4 | PROJECTION_MODE | |
  30035. * | 5 | SKYBOX_MODE | |
  30036. * | 6 | INVCUBIC_MODE | |
  30037. * | 7 | EQUIRECTANGULAR_MODE | |
  30038. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30039. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30040. */
  30041. set: function (value) {
  30042. if (this._coordinatesMode === value) {
  30043. return;
  30044. }
  30045. this._coordinatesMode = value;
  30046. if (this._scene) {
  30047. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30048. }
  30049. },
  30050. enumerable: true,
  30051. configurable: true
  30052. });
  30053. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30054. /**
  30055. * Gets whether or not the texture contains RGBD data.
  30056. */
  30057. get: function () {
  30058. return this._texture != null && this._texture._isRGBD;
  30059. },
  30060. enumerable: true,
  30061. configurable: true
  30062. });
  30063. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30064. get: function () {
  30065. if (this._texture)
  30066. return this._texture._lodGenerationOffset;
  30067. return 0.0;
  30068. },
  30069. set: function (value) {
  30070. if (this._texture)
  30071. this._texture._lodGenerationOffset = value;
  30072. },
  30073. enumerable: true,
  30074. configurable: true
  30075. });
  30076. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30077. get: function () {
  30078. if (this._texture)
  30079. return this._texture._lodGenerationScale;
  30080. return 0.0;
  30081. },
  30082. set: function (value) {
  30083. if (this._texture)
  30084. this._texture._lodGenerationScale = value;
  30085. },
  30086. enumerable: true,
  30087. configurable: true
  30088. });
  30089. Object.defineProperty(BaseTexture.prototype, "uid", {
  30090. get: function () {
  30091. if (!this._uid) {
  30092. this._uid = BABYLON.Tools.RandomId();
  30093. }
  30094. return this._uid;
  30095. },
  30096. enumerable: true,
  30097. configurable: true
  30098. });
  30099. BaseTexture.prototype.toString = function () {
  30100. return this.name;
  30101. };
  30102. BaseTexture.prototype.getClassName = function () {
  30103. return "BaseTexture";
  30104. };
  30105. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30106. set: function (callback) {
  30107. if (this._onDisposeObserver) {
  30108. this.onDisposeObservable.remove(this._onDisposeObserver);
  30109. }
  30110. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30111. },
  30112. enumerable: true,
  30113. configurable: true
  30114. });
  30115. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30116. get: function () {
  30117. return true;
  30118. },
  30119. enumerable: true,
  30120. configurable: true
  30121. });
  30122. BaseTexture.prototype.getScene = function () {
  30123. return this._scene;
  30124. };
  30125. BaseTexture.prototype.getTextureMatrix = function () {
  30126. return BABYLON.Matrix.IdentityReadOnly;
  30127. };
  30128. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30129. return BABYLON.Matrix.IdentityReadOnly;
  30130. };
  30131. BaseTexture.prototype.getInternalTexture = function () {
  30132. return this._texture;
  30133. };
  30134. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30135. return !this.isBlocking || this.isReady();
  30136. };
  30137. BaseTexture.prototype.isReady = function () {
  30138. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30139. this.delayLoad();
  30140. return false;
  30141. }
  30142. if (this._texture) {
  30143. return this._texture.isReady;
  30144. }
  30145. return false;
  30146. };
  30147. BaseTexture.prototype.getSize = function () {
  30148. if (this._texture) {
  30149. if (this._texture.width) {
  30150. this._cachedSize.width = this._texture.width;
  30151. this._cachedSize.height = this._texture.height;
  30152. return this._cachedSize;
  30153. }
  30154. if (this._texture._size) {
  30155. this._cachedSize.width = this._texture._size;
  30156. this._cachedSize.height = this._texture._size;
  30157. return this._cachedSize;
  30158. }
  30159. }
  30160. return this._cachedSize;
  30161. };
  30162. BaseTexture.prototype.getBaseSize = function () {
  30163. if (!this.isReady() || !this._texture)
  30164. return BABYLON.Size.Zero();
  30165. if (this._texture._size) {
  30166. return new BABYLON.Size(this._texture._size, this._texture._size);
  30167. }
  30168. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30169. };
  30170. BaseTexture.prototype.scale = function (ratio) {
  30171. };
  30172. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30173. get: function () {
  30174. return false;
  30175. },
  30176. enumerable: true,
  30177. configurable: true
  30178. });
  30179. /** @hidden */
  30180. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30181. if (!this._scene) {
  30182. return null;
  30183. }
  30184. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30185. for (var index = 0; index < texturesCache.length; index++) {
  30186. var texturesCacheEntry = texturesCache[index];
  30187. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30188. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30189. texturesCacheEntry.incrementReferences();
  30190. return texturesCacheEntry;
  30191. }
  30192. }
  30193. }
  30194. return null;
  30195. };
  30196. /** @hidden */
  30197. BaseTexture.prototype._rebuild = function () {
  30198. };
  30199. BaseTexture.prototype.delayLoad = function () {
  30200. };
  30201. BaseTexture.prototype.clone = function () {
  30202. return null;
  30203. };
  30204. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30205. get: function () {
  30206. if (!this._texture) {
  30207. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30208. }
  30209. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30210. },
  30211. enumerable: true,
  30212. configurable: true
  30213. });
  30214. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30215. get: function () {
  30216. if (!this._texture) {
  30217. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30218. }
  30219. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30220. },
  30221. enumerable: true,
  30222. configurable: true
  30223. });
  30224. /**
  30225. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30226. * This will returns an RGBA array buffer containing either in values (0-255) or
  30227. * float values (0-1) depending of the underlying buffer type.
  30228. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30229. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30230. * @param buffer defines a user defined buffer to fill with data (can be null)
  30231. * @returns The Array buffer containing the pixels data.
  30232. */
  30233. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30234. if (faceIndex === void 0) { faceIndex = 0; }
  30235. if (level === void 0) { level = 0; }
  30236. if (buffer === void 0) { buffer = null; }
  30237. if (!this._texture) {
  30238. return null;
  30239. }
  30240. var size = this.getSize();
  30241. var width = size.width;
  30242. var height = size.height;
  30243. var scene = this.getScene();
  30244. if (!scene) {
  30245. return null;
  30246. }
  30247. var engine = scene.getEngine();
  30248. if (level != 0) {
  30249. width = width / Math.pow(2, level);
  30250. height = height / Math.pow(2, level);
  30251. width = Math.round(width);
  30252. height = Math.round(height);
  30253. }
  30254. if (this._texture.isCube) {
  30255. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30256. }
  30257. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30258. };
  30259. BaseTexture.prototype.releaseInternalTexture = function () {
  30260. if (this._texture) {
  30261. this._texture.dispose();
  30262. this._texture = null;
  30263. }
  30264. };
  30265. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30266. get: function () {
  30267. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30268. return null;
  30269. }
  30270. if (!this._texture._sphericalPolynomial) {
  30271. this._texture._sphericalPolynomial =
  30272. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30273. }
  30274. return this._texture._sphericalPolynomial;
  30275. },
  30276. set: function (value) {
  30277. if (this._texture) {
  30278. this._texture._sphericalPolynomial = value;
  30279. }
  30280. },
  30281. enumerable: true,
  30282. configurable: true
  30283. });
  30284. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30285. get: function () {
  30286. if (this._texture) {
  30287. return this._texture._lodTextureHigh;
  30288. }
  30289. return null;
  30290. },
  30291. enumerable: true,
  30292. configurable: true
  30293. });
  30294. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30295. get: function () {
  30296. if (this._texture) {
  30297. return this._texture._lodTextureMid;
  30298. }
  30299. return null;
  30300. },
  30301. enumerable: true,
  30302. configurable: true
  30303. });
  30304. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30305. get: function () {
  30306. if (this._texture) {
  30307. return this._texture._lodTextureLow;
  30308. }
  30309. return null;
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. BaseTexture.prototype.dispose = function () {
  30315. if (!this._scene) {
  30316. return;
  30317. }
  30318. // Animations
  30319. this._scene.stopAnimation(this);
  30320. // Remove from scene
  30321. this._scene._removePendingData(this);
  30322. var index = this._scene.textures.indexOf(this);
  30323. if (index >= 0) {
  30324. this._scene.textures.splice(index, 1);
  30325. }
  30326. this._scene.onTextureRemovedObservable.notifyObservers(this);
  30327. if (this._texture === undefined) {
  30328. return;
  30329. }
  30330. // Release
  30331. this.releaseInternalTexture();
  30332. // Callback
  30333. this.onDisposeObservable.notifyObservers(this);
  30334. this.onDisposeObservable.clear();
  30335. };
  30336. BaseTexture.prototype.serialize = function () {
  30337. if (!this.name) {
  30338. return null;
  30339. }
  30340. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30341. // Animations
  30342. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30343. return serializationObject;
  30344. };
  30345. BaseTexture.WhenAllReady = function (textures, callback) {
  30346. var numRemaining = textures.length;
  30347. if (numRemaining === 0) {
  30348. callback();
  30349. return;
  30350. }
  30351. var _loop_1 = function () {
  30352. texture = textures[i];
  30353. if (texture.isReady()) {
  30354. if (--numRemaining === 0) {
  30355. callback();
  30356. }
  30357. }
  30358. else {
  30359. onLoadObservable = texture.onLoadObservable;
  30360. var onLoadCallback_1 = function () {
  30361. onLoadObservable.removeCallback(onLoadCallback_1);
  30362. if (--numRemaining === 0) {
  30363. callback();
  30364. }
  30365. };
  30366. onLoadObservable.add(onLoadCallback_1);
  30367. }
  30368. };
  30369. var texture, onLoadObservable;
  30370. for (var i = 0; i < textures.length; i++) {
  30371. _loop_1();
  30372. }
  30373. };
  30374. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30375. __decorate([
  30376. BABYLON.serialize()
  30377. ], BaseTexture.prototype, "name", void 0);
  30378. __decorate([
  30379. BABYLON.serialize("hasAlpha")
  30380. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30381. __decorate([
  30382. BABYLON.serialize()
  30383. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30384. __decorate([
  30385. BABYLON.serialize()
  30386. ], BaseTexture.prototype, "level", void 0);
  30387. __decorate([
  30388. BABYLON.serialize()
  30389. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30390. __decorate([
  30391. BABYLON.serialize("coordinatesMode")
  30392. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30393. __decorate([
  30394. BABYLON.serialize()
  30395. ], BaseTexture.prototype, "wrapU", void 0);
  30396. __decorate([
  30397. BABYLON.serialize()
  30398. ], BaseTexture.prototype, "wrapV", void 0);
  30399. __decorate([
  30400. BABYLON.serialize()
  30401. ], BaseTexture.prototype, "wrapR", void 0);
  30402. __decorate([
  30403. BABYLON.serialize()
  30404. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30405. __decorate([
  30406. BABYLON.serialize()
  30407. ], BaseTexture.prototype, "isCube", void 0);
  30408. __decorate([
  30409. BABYLON.serialize()
  30410. ], BaseTexture.prototype, "is3D", void 0);
  30411. __decorate([
  30412. BABYLON.serialize()
  30413. ], BaseTexture.prototype, "gammaSpace", void 0);
  30414. __decorate([
  30415. BABYLON.serialize()
  30416. ], BaseTexture.prototype, "invertZ", void 0);
  30417. __decorate([
  30418. BABYLON.serialize()
  30419. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30420. __decorate([
  30421. BABYLON.serialize()
  30422. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30423. __decorate([
  30424. BABYLON.serialize()
  30425. ], BaseTexture.prototype, "lodGenerationScale", null);
  30426. __decorate([
  30427. BABYLON.serialize()
  30428. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30429. return BaseTexture;
  30430. }());
  30431. BABYLON.BaseTexture = BaseTexture;
  30432. })(BABYLON || (BABYLON = {}));
  30433. //# sourceMappingURL=babylon.baseTexture.js.map
  30434. var BABYLON;
  30435. (function (BABYLON) {
  30436. var Texture = /** @class */ (function (_super) {
  30437. __extends(Texture, _super);
  30438. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30439. if (noMipmap === void 0) { noMipmap = false; }
  30440. if (invertY === void 0) { invertY = true; }
  30441. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30442. if (onLoad === void 0) { onLoad = null; }
  30443. if (onError === void 0) { onError = null; }
  30444. if (buffer === void 0) { buffer = null; }
  30445. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30446. var _this = _super.call(this, scene) || this;
  30447. _this.uOffset = 0;
  30448. _this.vOffset = 0;
  30449. _this.uScale = 1.0;
  30450. _this.vScale = 1.0;
  30451. _this.uAng = 0;
  30452. _this.vAng = 0;
  30453. _this.wAng = 0;
  30454. /**
  30455. * Defines the center of rotation (U)
  30456. */
  30457. _this.uRotationCenter = 0.5;
  30458. /**
  30459. * Defines the center of rotation (V)
  30460. */
  30461. _this.vRotationCenter = 0.5;
  30462. /**
  30463. * Defines the center of rotation (W)
  30464. */
  30465. _this.wRotationCenter = 0.5;
  30466. _this._isBlocking = true;
  30467. _this.name = url || "";
  30468. _this.url = url;
  30469. _this._noMipmap = noMipmap;
  30470. _this._invertY = invertY;
  30471. _this._samplingMode = samplingMode;
  30472. _this._buffer = buffer;
  30473. _this._deleteBuffer = deleteBuffer;
  30474. if (format) {
  30475. _this._format = format;
  30476. }
  30477. scene = _this.getScene();
  30478. if (!scene) {
  30479. return _this;
  30480. }
  30481. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30482. var load = function () {
  30483. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30484. _this.onLoadObservable.notifyObservers(_this);
  30485. }
  30486. if (onLoad) {
  30487. onLoad();
  30488. }
  30489. if (!_this.isBlocking && scene) {
  30490. scene.resetCachedMaterial();
  30491. }
  30492. };
  30493. if (!_this.url) {
  30494. _this._delayedOnLoad = load;
  30495. _this._delayedOnError = onError;
  30496. return _this;
  30497. }
  30498. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30499. if (!_this._texture) {
  30500. if (!scene.useDelayedTextureLoading) {
  30501. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30502. if (deleteBuffer) {
  30503. delete _this._buffer;
  30504. }
  30505. }
  30506. else {
  30507. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30508. _this._delayedOnLoad = load;
  30509. _this._delayedOnError = onError;
  30510. }
  30511. }
  30512. else {
  30513. if (_this._texture.isReady) {
  30514. BABYLON.Tools.SetImmediate(function () { return load(); });
  30515. }
  30516. else {
  30517. _this._texture.onLoadedObservable.add(load);
  30518. }
  30519. }
  30520. return _this;
  30521. }
  30522. Object.defineProperty(Texture.prototype, "noMipmap", {
  30523. get: function () {
  30524. return this._noMipmap;
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. Object.defineProperty(Texture.prototype, "isBlocking", {
  30530. get: function () {
  30531. return this._isBlocking;
  30532. },
  30533. set: function (value) {
  30534. this._isBlocking = value;
  30535. },
  30536. enumerable: true,
  30537. configurable: true
  30538. });
  30539. Object.defineProperty(Texture.prototype, "samplingMode", {
  30540. get: function () {
  30541. return this._samplingMode;
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. /**
  30547. * Update the url (and optional buffer) of this texture if url was null during construction.
  30548. * @param url the url of the texture
  30549. * @param buffer the buffer of the texture (defaults to null)
  30550. */
  30551. Texture.prototype.updateURL = function (url, buffer) {
  30552. if (buffer === void 0) { buffer = null; }
  30553. if (this.url) {
  30554. throw new Error("URL is already set");
  30555. }
  30556. this.url = url;
  30557. this._buffer = buffer;
  30558. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30559. this.delayLoad();
  30560. };
  30561. Texture.prototype.delayLoad = function () {
  30562. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30563. return;
  30564. }
  30565. var scene = this.getScene();
  30566. if (!scene) {
  30567. return;
  30568. }
  30569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30570. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30571. if (!this._texture) {
  30572. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30573. if (this._deleteBuffer) {
  30574. delete this._buffer;
  30575. }
  30576. }
  30577. else {
  30578. if (this._delayedOnLoad) {
  30579. if (this._texture.isReady) {
  30580. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30581. }
  30582. else {
  30583. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30584. }
  30585. }
  30586. }
  30587. this._delayedOnLoad = null;
  30588. this._delayedOnError = null;
  30589. };
  30590. /**
  30591. * Default is Trilinear mode.
  30592. *
  30593. * | Value | Type | Description |
  30594. * | ----- | ------------------ | ----------- |
  30595. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30596. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30597. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30598. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30599. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30600. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30601. * | 7 | NEAREST_LINEAR | |
  30602. * | 8 | NEAREST_NEAREST | |
  30603. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30604. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30605. * | 11 | LINEAR_LINEAR | |
  30606. * | 12 | LINEAR_NEAREST | |
  30607. *
  30608. * > _mag_: magnification filter (close to the viewer)
  30609. * > _min_: minification filter (far from the viewer)
  30610. * > _mip_: filter used between mip map levels
  30611. *
  30612. */
  30613. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30614. if (!this._texture) {
  30615. return;
  30616. }
  30617. var scene = this.getScene();
  30618. if (!scene) {
  30619. return;
  30620. }
  30621. this._samplingMode = samplingMode;
  30622. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30623. };
  30624. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30625. x *= this.uScale;
  30626. y *= this.vScale;
  30627. x -= this.uRotationCenter * this.uScale;
  30628. y -= this.vRotationCenter * this.vScale;
  30629. z -= this.wRotationCenter;
  30630. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30631. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30632. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30633. t.z += this.wRotationCenter;
  30634. };
  30635. Texture.prototype.getTextureMatrix = function () {
  30636. var _this = this;
  30637. if (this.uOffset === this._cachedUOffset &&
  30638. this.vOffset === this._cachedVOffset &&
  30639. this.uScale === this._cachedUScale &&
  30640. this.vScale === this._cachedVScale &&
  30641. this.uAng === this._cachedUAng &&
  30642. this.vAng === this._cachedVAng &&
  30643. this.wAng === this._cachedWAng) {
  30644. return this._cachedTextureMatrix;
  30645. }
  30646. this._cachedUOffset = this.uOffset;
  30647. this._cachedVOffset = this.vOffset;
  30648. this._cachedUScale = this.uScale;
  30649. this._cachedVScale = this.vScale;
  30650. this._cachedUAng = this.uAng;
  30651. this._cachedVAng = this.vAng;
  30652. this._cachedWAng = this.wAng;
  30653. if (!this._cachedTextureMatrix) {
  30654. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30655. this._rowGenerationMatrix = new BABYLON.Matrix();
  30656. this._t0 = BABYLON.Vector3.Zero();
  30657. this._t1 = BABYLON.Vector3.Zero();
  30658. this._t2 = BABYLON.Vector3.Zero();
  30659. }
  30660. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30661. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30662. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30663. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30664. this._t1.subtractInPlace(this._t0);
  30665. this._t2.subtractInPlace(this._t0);
  30666. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30667. this._cachedTextureMatrix.m[0] = this._t1.x;
  30668. this._cachedTextureMatrix.m[1] = this._t1.y;
  30669. this._cachedTextureMatrix.m[2] = this._t1.z;
  30670. this._cachedTextureMatrix.m[4] = this._t2.x;
  30671. this._cachedTextureMatrix.m[5] = this._t2.y;
  30672. this._cachedTextureMatrix.m[6] = this._t2.z;
  30673. this._cachedTextureMatrix.m[8] = this._t0.x;
  30674. this._cachedTextureMatrix.m[9] = this._t0.y;
  30675. this._cachedTextureMatrix.m[10] = this._t0.z;
  30676. var scene = this.getScene();
  30677. if (!scene) {
  30678. return this._cachedTextureMatrix;
  30679. }
  30680. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30681. return mat.hasTexture(_this);
  30682. });
  30683. return this._cachedTextureMatrix;
  30684. };
  30685. Texture.prototype.getReflectionTextureMatrix = function () {
  30686. var _this = this;
  30687. var scene = this.getScene();
  30688. if (!scene) {
  30689. return this._cachedTextureMatrix;
  30690. }
  30691. if (this.uOffset === this._cachedUOffset &&
  30692. this.vOffset === this._cachedVOffset &&
  30693. this.uScale === this._cachedUScale &&
  30694. this.vScale === this._cachedVScale &&
  30695. this.coordinatesMode === this._cachedCoordinatesMode) {
  30696. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30697. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30698. return this._cachedTextureMatrix;
  30699. }
  30700. }
  30701. else {
  30702. return this._cachedTextureMatrix;
  30703. }
  30704. }
  30705. if (!this._cachedTextureMatrix) {
  30706. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30707. }
  30708. if (!this._projectionModeMatrix) {
  30709. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30710. }
  30711. this._cachedUOffset = this.uOffset;
  30712. this._cachedVOffset = this.vOffset;
  30713. this._cachedUScale = this.uScale;
  30714. this._cachedVScale = this.vScale;
  30715. this._cachedCoordinatesMode = this.coordinatesMode;
  30716. switch (this.coordinatesMode) {
  30717. case Texture.PLANAR_MODE:
  30718. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30719. this._cachedTextureMatrix[0] = this.uScale;
  30720. this._cachedTextureMatrix[5] = this.vScale;
  30721. this._cachedTextureMatrix[12] = this.uOffset;
  30722. this._cachedTextureMatrix[13] = this.vOffset;
  30723. break;
  30724. case Texture.PROJECTION_MODE:
  30725. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30726. this._projectionModeMatrix.m[0] = 0.5;
  30727. this._projectionModeMatrix.m[5] = -0.5;
  30728. this._projectionModeMatrix.m[10] = 0.0;
  30729. this._projectionModeMatrix.m[12] = 0.5;
  30730. this._projectionModeMatrix.m[13] = 0.5;
  30731. this._projectionModeMatrix.m[14] = 1.0;
  30732. this._projectionModeMatrix.m[15] = 1.0;
  30733. var projectionMatrix = scene.getProjectionMatrix();
  30734. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30735. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30736. break;
  30737. default:
  30738. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30739. break;
  30740. }
  30741. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30742. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30743. });
  30744. return this._cachedTextureMatrix;
  30745. };
  30746. Texture.prototype.clone = function () {
  30747. var _this = this;
  30748. return BABYLON.SerializationHelper.Clone(function () {
  30749. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30750. }, this);
  30751. };
  30752. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30753. get: function () {
  30754. if (!this._onLoadObservable) {
  30755. this._onLoadObservable = new BABYLON.Observable();
  30756. }
  30757. return this._onLoadObservable;
  30758. },
  30759. enumerable: true,
  30760. configurable: true
  30761. });
  30762. Texture.prototype.serialize = function () {
  30763. var serializationObject = _super.prototype.serialize.call(this);
  30764. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30765. serializationObject.base64String = this._buffer;
  30766. serializationObject.name = serializationObject.name.replace("data:", "");
  30767. }
  30768. serializationObject.invertY = this._invertY;
  30769. serializationObject.samplingMode = this.samplingMode;
  30770. return serializationObject;
  30771. };
  30772. Texture.prototype.getClassName = function () {
  30773. return "Texture";
  30774. };
  30775. Texture.prototype.dispose = function () {
  30776. _super.prototype.dispose.call(this);
  30777. if (this._onLoadObservable) {
  30778. this._onLoadObservable.clear();
  30779. this._onLoadObservable = null;
  30780. }
  30781. this._delayedOnLoad = null;
  30782. this._delayedOnError = null;
  30783. };
  30784. // Statics
  30785. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30786. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30787. if (onLoad === void 0) { onLoad = null; }
  30788. if (onError === void 0) { onError = null; }
  30789. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30790. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30791. };
  30792. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30793. if (parsedTexture.customType) {
  30794. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30795. // Update Sampling Mode
  30796. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30797. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30798. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30799. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30800. }
  30801. }
  30802. return parsedCustomTexture;
  30803. }
  30804. if (parsedTexture.isCube) {
  30805. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30806. }
  30807. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30808. return null;
  30809. }
  30810. var texture = BABYLON.SerializationHelper.Parse(function () {
  30811. var generateMipMaps = true;
  30812. if (parsedTexture.noMipmap) {
  30813. generateMipMaps = false;
  30814. }
  30815. if (parsedTexture.mirrorPlane) {
  30816. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30817. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30818. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30819. return mirrorTexture;
  30820. }
  30821. else if (parsedTexture.isRenderTarget) {
  30822. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30823. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30824. return renderTargetTexture;
  30825. }
  30826. else {
  30827. var texture;
  30828. if (parsedTexture.base64String) {
  30829. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30830. }
  30831. else {
  30832. var url = rootUrl + parsedTexture.name;
  30833. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30834. url = parsedTexture.url;
  30835. }
  30836. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30837. }
  30838. return texture;
  30839. }
  30840. }, parsedTexture, scene);
  30841. // Update Sampling Mode
  30842. if (parsedTexture.samplingMode) {
  30843. var sampling = parsedTexture.samplingMode;
  30844. if (texture._samplingMode !== sampling) {
  30845. texture.updateSamplingMode(sampling);
  30846. }
  30847. }
  30848. // Animations
  30849. if (parsedTexture.animations) {
  30850. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30851. var parsedAnimation = parsedTexture.animations[animationIndex];
  30852. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30853. }
  30854. }
  30855. return texture;
  30856. };
  30857. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30858. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30859. if (noMipmap === void 0) { noMipmap = false; }
  30860. if (invertY === void 0) { invertY = true; }
  30861. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30862. if (onLoad === void 0) { onLoad = null; }
  30863. if (onError === void 0) { onError = null; }
  30864. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30865. if (name.substr(0, 5) !== "data:") {
  30866. name = "data:" + name;
  30867. }
  30868. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30869. };
  30870. // Constants
  30871. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30872. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30873. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30874. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30875. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30876. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30877. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30878. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30879. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30880. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30881. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30882. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30883. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30884. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30885. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30886. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30887. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30888. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30889. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30890. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30891. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30892. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30893. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30894. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30895. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30896. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30897. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30898. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30899. /**
  30900. * 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
  30901. */
  30902. Texture.UseSerializedUrlIfAny = false;
  30903. __decorate([
  30904. BABYLON.serialize()
  30905. ], Texture.prototype, "url", void 0);
  30906. __decorate([
  30907. BABYLON.serialize()
  30908. ], Texture.prototype, "uOffset", void 0);
  30909. __decorate([
  30910. BABYLON.serialize()
  30911. ], Texture.prototype, "vOffset", void 0);
  30912. __decorate([
  30913. BABYLON.serialize()
  30914. ], Texture.prototype, "uScale", void 0);
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], Texture.prototype, "vScale", void 0);
  30918. __decorate([
  30919. BABYLON.serialize()
  30920. ], Texture.prototype, "uAng", void 0);
  30921. __decorate([
  30922. BABYLON.serialize()
  30923. ], Texture.prototype, "vAng", void 0);
  30924. __decorate([
  30925. BABYLON.serialize()
  30926. ], Texture.prototype, "wAng", void 0);
  30927. __decorate([
  30928. BABYLON.serialize()
  30929. ], Texture.prototype, "uRotationCenter", void 0);
  30930. __decorate([
  30931. BABYLON.serialize()
  30932. ], Texture.prototype, "vRotationCenter", void 0);
  30933. __decorate([
  30934. BABYLON.serialize()
  30935. ], Texture.prototype, "wRotationCenter", void 0);
  30936. __decorate([
  30937. BABYLON.serialize()
  30938. ], Texture.prototype, "isBlocking", null);
  30939. return Texture;
  30940. }(BABYLON.BaseTexture));
  30941. BABYLON.Texture = Texture;
  30942. })(BABYLON || (BABYLON = {}));
  30943. //# sourceMappingURL=babylon.texture.js.map
  30944. var BABYLON;
  30945. (function (BABYLON) {
  30946. /**
  30947. * @hidden
  30948. **/
  30949. var _InstancesBatch = /** @class */ (function () {
  30950. function _InstancesBatch() {
  30951. this.mustReturn = false;
  30952. this.visibleInstances = new Array();
  30953. this.renderSelf = new Array();
  30954. }
  30955. return _InstancesBatch;
  30956. }());
  30957. BABYLON._InstancesBatch = _InstancesBatch;
  30958. /**
  30959. * Class used to represent renderable models
  30960. */
  30961. var Mesh = /** @class */ (function (_super) {
  30962. __extends(Mesh, _super);
  30963. /**
  30964. * @constructor
  30965. * @param name The value used by scene.getMeshByName() to do a lookup.
  30966. * @param scene The scene to add this mesh to.
  30967. * @param parent The parent of this mesh, if it has one
  30968. * @param source An optional Mesh from which geometry is shared, cloned.
  30969. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30970. * When false, achieved by calling a clone(), also passing False.
  30971. * This will make creation of children, recursive.
  30972. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30973. */
  30974. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30975. if (scene === void 0) { scene = null; }
  30976. if (parent === void 0) { parent = null; }
  30977. if (source === void 0) { source = null; }
  30978. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30979. var _this = _super.call(this, name, scene) || this;
  30980. // Members
  30981. /**
  30982. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30983. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30984. */
  30985. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30986. /**
  30987. * Gets the list of instances created from this mesh
  30988. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30989. */
  30990. _this.instances = new Array();
  30991. _this._LODLevels = new Array();
  30992. /** @hidden */
  30993. _this._visibleInstances = {};
  30994. _this._renderIdForInstances = new Array();
  30995. _this._batchCache = new _InstancesBatch();
  30996. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30997. // Use by builder only to know what orientation were the mesh build in.
  30998. /** @hidden */
  30999. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31000. /**
  31001. * Use this property to change the original side orientation defined at construction time
  31002. */
  31003. _this.overrideMaterialSideOrientation = null;
  31004. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31005. // Will be used to save a source mesh reference, If any
  31006. _this._source = null;
  31007. scene = _this.getScene();
  31008. if (source) {
  31009. // Geometry
  31010. if (source._geometry) {
  31011. source._geometry.applyToMesh(_this);
  31012. }
  31013. // Deep copy
  31014. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31015. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31016. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31017. ], ["_poseMatrix"]);
  31018. // Source mesh
  31019. _this._source = source;
  31020. // Construction Params
  31021. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31022. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31023. var myAnyThis = _this;
  31024. var myAnySource = source;
  31025. myAnyThis._closePath = myAnySource._closePath;
  31026. myAnyThis._idx = myAnySource._idx;
  31027. myAnyThis.dashSize = myAnySource.dashSize;
  31028. myAnyThis.gapSize = myAnySource.gapSize;
  31029. myAnyThis.path3D = myAnySource.path3D;
  31030. myAnyThis.pathArray = myAnySource.pathArray;
  31031. myAnyThis.arc = myAnySource.arc;
  31032. myAnyThis.radius = myAnySource.radius;
  31033. // Animation ranges
  31034. if (_this._source._ranges) {
  31035. var ranges = _this._source._ranges;
  31036. for (var name in ranges) {
  31037. if (!ranges.hasOwnProperty(name)) {
  31038. continue;
  31039. }
  31040. if (!ranges[name]) {
  31041. continue;
  31042. }
  31043. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31044. }
  31045. }
  31046. // Metadata
  31047. if (source.metadata && source.metadata.clone) {
  31048. _this.metadata = source.metadata.clone();
  31049. }
  31050. else {
  31051. _this.metadata = source.metadata;
  31052. }
  31053. // Tags
  31054. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31055. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31056. }
  31057. // Parent
  31058. _this.parent = source.parent;
  31059. // Pivot
  31060. _this.setPivotMatrix(source.getPivotMatrix());
  31061. _this.id = name + "." + source.id;
  31062. // Material
  31063. _this.material = source.material;
  31064. var index;
  31065. if (!doNotCloneChildren) {
  31066. // Children
  31067. var directDescendants = source.getDescendants(true);
  31068. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31069. var child = directDescendants[index_1];
  31070. if (child.clone) {
  31071. child.clone(name + "." + child.name, _this);
  31072. }
  31073. }
  31074. }
  31075. // Physics clone
  31076. var physicsEngine = _this.getScene().getPhysicsEngine();
  31077. if (clonePhysicsImpostor && physicsEngine) {
  31078. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31079. if (impostor) {
  31080. _this.physicsImpostor = impostor.clone(_this);
  31081. }
  31082. }
  31083. // Particles
  31084. for (index = 0; index < scene.particleSystems.length; index++) {
  31085. var system = scene.particleSystems[index];
  31086. if (system.emitter === source) {
  31087. system.clone(system.name, _this);
  31088. }
  31089. }
  31090. _this.refreshBoundingInfo();
  31091. _this.computeWorldMatrix(true);
  31092. }
  31093. // Parent
  31094. if (parent !== null) {
  31095. _this.parent = parent;
  31096. }
  31097. return _this;
  31098. }
  31099. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31100. /**
  31101. * An event triggered before rendering the mesh
  31102. */
  31103. get: function () {
  31104. if (!this._onBeforeRenderObservable) {
  31105. this._onBeforeRenderObservable = new BABYLON.Observable();
  31106. }
  31107. return this._onBeforeRenderObservable;
  31108. },
  31109. enumerable: true,
  31110. configurable: true
  31111. });
  31112. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31113. /**
  31114. * An event triggered after rendering the mesh
  31115. */
  31116. get: function () {
  31117. if (!this._onAfterRenderObservable) {
  31118. this._onAfterRenderObservable = new BABYLON.Observable();
  31119. }
  31120. return this._onAfterRenderObservable;
  31121. },
  31122. enumerable: true,
  31123. configurable: true
  31124. });
  31125. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31126. /**
  31127. * An event triggered before drawing the mesh
  31128. */
  31129. get: function () {
  31130. if (!this._onBeforeDrawObservable) {
  31131. this._onBeforeDrawObservable = new BABYLON.Observable();
  31132. }
  31133. return this._onBeforeDrawObservable;
  31134. },
  31135. enumerable: true,
  31136. configurable: true
  31137. });
  31138. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31139. /**
  31140. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31141. */
  31142. set: function (callback) {
  31143. if (this._onBeforeDrawObserver) {
  31144. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31145. }
  31146. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31147. },
  31148. enumerable: true,
  31149. configurable: true
  31150. });
  31151. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31152. /**
  31153. * Gets or sets the morph target manager
  31154. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31155. */
  31156. get: function () {
  31157. return this._morphTargetManager;
  31158. },
  31159. set: function (value) {
  31160. if (this._morphTargetManager === value) {
  31161. return;
  31162. }
  31163. this._morphTargetManager = value;
  31164. this._syncGeometryWithMorphTargetManager();
  31165. },
  31166. enumerable: true,
  31167. configurable: true
  31168. });
  31169. Object.defineProperty(Mesh.prototype, "source", {
  31170. /**
  31171. * Gets the source mesh (the one used to clone this one from)
  31172. */
  31173. get: function () {
  31174. return this._source;
  31175. },
  31176. enumerable: true,
  31177. configurable: true
  31178. });
  31179. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31180. /**
  31181. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31182. */
  31183. get: function () {
  31184. return this._unIndexed;
  31185. },
  31186. set: function (value) {
  31187. if (this._unIndexed !== value) {
  31188. this._unIndexed = value;
  31189. this._markSubMeshesAsAttributesDirty();
  31190. }
  31191. },
  31192. enumerable: true,
  31193. configurable: true
  31194. });
  31195. // Methods
  31196. /**
  31197. * Gets the class name
  31198. * @returns the string "Mesh".
  31199. */
  31200. Mesh.prototype.getClassName = function () {
  31201. return "Mesh";
  31202. };
  31203. /**
  31204. * Returns a description of this mesh
  31205. * @param fullDetails define if full details about this mesh must be used
  31206. * @returns a descriptive string representing this mesh
  31207. */
  31208. Mesh.prototype.toString = function (fullDetails) {
  31209. var ret = _super.prototype.toString.call(this, fullDetails);
  31210. ret += ", n vertices: " + this.getTotalVertices();
  31211. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31212. if (this.animations) {
  31213. for (var i = 0; i < this.animations.length; i++) {
  31214. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31215. }
  31216. }
  31217. if (fullDetails) {
  31218. if (this._geometry) {
  31219. var ib = this.getIndices();
  31220. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31221. if (vb && ib) {
  31222. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31223. }
  31224. }
  31225. else {
  31226. ret += ", flat shading: UNKNOWN";
  31227. }
  31228. }
  31229. return ret;
  31230. };
  31231. /** @hidden */
  31232. Mesh.prototype._unBindEffect = function () {
  31233. _super.prototype._unBindEffect.call(this);
  31234. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31235. var instance = _a[_i];
  31236. instance._unBindEffect();
  31237. }
  31238. };
  31239. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31240. /**
  31241. * Gets a boolean indicating if this mesh has LOD
  31242. */
  31243. get: function () {
  31244. return this._LODLevels.length > 0;
  31245. },
  31246. enumerable: true,
  31247. configurable: true
  31248. });
  31249. /**
  31250. * Gets the list of MeshLODLevel associated with the current mesh
  31251. * @returns an array of MeshLODLevel
  31252. */
  31253. Mesh.prototype.getLODLevels = function () {
  31254. return this._LODLevels;
  31255. };
  31256. Mesh.prototype._sortLODLevels = function () {
  31257. this._LODLevels.sort(function (a, b) {
  31258. if (a.distance < b.distance) {
  31259. return 1;
  31260. }
  31261. if (a.distance > b.distance) {
  31262. return -1;
  31263. }
  31264. return 0;
  31265. });
  31266. };
  31267. /**
  31268. * Add a mesh as LOD level triggered at the given distance.
  31269. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31270. * @param distance The distance from the center of the object to show this level
  31271. * @param mesh The mesh to be added as LOD level (can be null)
  31272. * @return This mesh (for chaining)
  31273. */
  31274. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31275. if (mesh && mesh._masterMesh) {
  31276. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31277. return this;
  31278. }
  31279. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31280. this._LODLevels.push(level);
  31281. if (mesh) {
  31282. mesh._masterMesh = this;
  31283. }
  31284. this._sortLODLevels();
  31285. return this;
  31286. };
  31287. /**
  31288. * Returns the LOD level mesh at the passed distance or null if not found.
  31289. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31290. * @param distance The distance from the center of the object to show this level
  31291. * @returns a Mesh or `null`
  31292. */
  31293. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31294. for (var index = 0; index < this._LODLevels.length; index++) {
  31295. var level = this._LODLevels[index];
  31296. if (level.distance === distance) {
  31297. return level.mesh;
  31298. }
  31299. }
  31300. return null;
  31301. };
  31302. /**
  31303. * Remove a mesh from the LOD array
  31304. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31305. * @param mesh defines the mesh to be removed
  31306. * @return This mesh (for chaining)
  31307. */
  31308. Mesh.prototype.removeLODLevel = function (mesh) {
  31309. for (var index = 0; index < this._LODLevels.length; index++) {
  31310. if (this._LODLevels[index].mesh === mesh) {
  31311. this._LODLevels.splice(index, 1);
  31312. if (mesh) {
  31313. mesh._masterMesh = null;
  31314. }
  31315. }
  31316. }
  31317. this._sortLODLevels();
  31318. return this;
  31319. };
  31320. /**
  31321. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31322. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31323. * @param camera defines the camera to use to compute distance
  31324. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31325. * @return This mesh (for chaining)
  31326. */
  31327. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31328. if (!this._LODLevels || this._LODLevels.length === 0) {
  31329. return this;
  31330. }
  31331. var bSphere;
  31332. if (boundingSphere) {
  31333. bSphere = boundingSphere;
  31334. }
  31335. else {
  31336. var boundingInfo = this.getBoundingInfo();
  31337. bSphere = boundingInfo.boundingSphere;
  31338. }
  31339. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31340. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31341. if (this.onLODLevelSelection) {
  31342. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31343. }
  31344. return this;
  31345. }
  31346. for (var index = 0; index < this._LODLevels.length; index++) {
  31347. var level = this._LODLevels[index];
  31348. if (level.distance < distanceToCamera) {
  31349. if (level.mesh) {
  31350. level.mesh._preActivate();
  31351. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31352. }
  31353. if (this.onLODLevelSelection) {
  31354. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31355. }
  31356. return level.mesh;
  31357. }
  31358. }
  31359. if (this.onLODLevelSelection) {
  31360. this.onLODLevelSelection(distanceToCamera, this, this);
  31361. }
  31362. return this;
  31363. };
  31364. Object.defineProperty(Mesh.prototype, "geometry", {
  31365. /**
  31366. * Gets the mesh internal Geometry object
  31367. */
  31368. get: function () {
  31369. return this._geometry;
  31370. },
  31371. enumerable: true,
  31372. configurable: true
  31373. });
  31374. /**
  31375. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31376. * @returns the total number of vertices
  31377. */
  31378. Mesh.prototype.getTotalVertices = function () {
  31379. if (this._geometry === null || this._geometry === undefined) {
  31380. return 0;
  31381. }
  31382. return this._geometry.getTotalVertices();
  31383. };
  31384. /**
  31385. * Returns the content of an associated vertex buffer
  31386. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31387. * - BABYLON.VertexBuffer.PositionKind
  31388. * - BABYLON.VertexBuffer.UVKind
  31389. * - BABYLON.VertexBuffer.UV2Kind
  31390. * - BABYLON.VertexBuffer.UV3Kind
  31391. * - BABYLON.VertexBuffer.UV4Kind
  31392. * - BABYLON.VertexBuffer.UV5Kind
  31393. * - BABYLON.VertexBuffer.UV6Kind
  31394. * - BABYLON.VertexBuffer.ColorKind
  31395. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31396. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31397. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31398. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31399. * @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
  31400. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31401. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31402. */
  31403. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31404. if (!this._geometry) {
  31405. return null;
  31406. }
  31407. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31408. };
  31409. /**
  31410. * Returns the mesh VertexBuffer object from the requested `kind`
  31411. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31412. * - BABYLON.VertexBuffer.PositionKind
  31413. * - BABYLON.VertexBuffer.UVKind
  31414. * - BABYLON.VertexBuffer.UV2Kind
  31415. * - BABYLON.VertexBuffer.UV3Kind
  31416. * - BABYLON.VertexBuffer.UV4Kind
  31417. * - BABYLON.VertexBuffer.UV5Kind
  31418. * - BABYLON.VertexBuffer.UV6Kind
  31419. * - BABYLON.VertexBuffer.ColorKind
  31420. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31421. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31422. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31423. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31424. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31425. */
  31426. Mesh.prototype.getVertexBuffer = function (kind) {
  31427. if (!this._geometry) {
  31428. return null;
  31429. }
  31430. return this._geometry.getVertexBuffer(kind);
  31431. };
  31432. /**
  31433. * Tests if a specific vertex buffer is associated with this mesh
  31434. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31435. * - BABYLON.VertexBuffer.PositionKind
  31436. * - BABYLON.VertexBuffer.UVKind
  31437. * - BABYLON.VertexBuffer.UV2Kind
  31438. * - BABYLON.VertexBuffer.UV3Kind
  31439. * - BABYLON.VertexBuffer.UV4Kind
  31440. * - BABYLON.VertexBuffer.UV5Kind
  31441. * - BABYLON.VertexBuffer.UV6Kind
  31442. * - BABYLON.VertexBuffer.ColorKind
  31443. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31444. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31445. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31446. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31447. * @returns a boolean
  31448. */
  31449. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31450. if (!this._geometry) {
  31451. if (this._delayInfo) {
  31452. return this._delayInfo.indexOf(kind) !== -1;
  31453. }
  31454. return false;
  31455. }
  31456. return this._geometry.isVerticesDataPresent(kind);
  31457. };
  31458. /**
  31459. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31460. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31461. * - BABYLON.VertexBuffer.PositionKind
  31462. * - BABYLON.VertexBuffer.UVKind
  31463. * - BABYLON.VertexBuffer.UV2Kind
  31464. * - BABYLON.VertexBuffer.UV3Kind
  31465. * - BABYLON.VertexBuffer.UV4Kind
  31466. * - BABYLON.VertexBuffer.UV5Kind
  31467. * - BABYLON.VertexBuffer.UV6Kind
  31468. * - BABYLON.VertexBuffer.ColorKind
  31469. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31470. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31471. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31472. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31473. * @returns a boolean
  31474. */
  31475. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31476. if (!this._geometry) {
  31477. if (this._delayInfo) {
  31478. return this._delayInfo.indexOf(kind) !== -1;
  31479. }
  31480. return false;
  31481. }
  31482. return this._geometry.isVertexBufferUpdatable(kind);
  31483. };
  31484. /**
  31485. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31486. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31487. * - BABYLON.VertexBuffer.PositionKind
  31488. * - BABYLON.VertexBuffer.UVKind
  31489. * - BABYLON.VertexBuffer.UV2Kind
  31490. * - BABYLON.VertexBuffer.UV3Kind
  31491. * - BABYLON.VertexBuffer.UV4Kind
  31492. * - BABYLON.VertexBuffer.UV5Kind
  31493. * - BABYLON.VertexBuffer.UV6Kind
  31494. * - BABYLON.VertexBuffer.ColorKind
  31495. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31496. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31497. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31498. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31499. * @returns an array of strings
  31500. */
  31501. Mesh.prototype.getVerticesDataKinds = function () {
  31502. if (!this._geometry) {
  31503. var result = new Array();
  31504. if (this._delayInfo) {
  31505. this._delayInfo.forEach(function (kind, index, array) {
  31506. result.push(kind);
  31507. });
  31508. }
  31509. return result;
  31510. }
  31511. return this._geometry.getVerticesDataKinds();
  31512. };
  31513. /**
  31514. * Returns a positive integer : the total number of indices in this mesh geometry.
  31515. * @returns the numner of indices or zero if the mesh has no geometry.
  31516. */
  31517. Mesh.prototype.getTotalIndices = function () {
  31518. if (!this._geometry) {
  31519. return 0;
  31520. }
  31521. return this._geometry.getTotalIndices();
  31522. };
  31523. /**
  31524. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31525. * @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.
  31526. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31527. * @returns the indices array or an empty array if the mesh has no geometry
  31528. */
  31529. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31530. if (!this._geometry) {
  31531. return [];
  31532. }
  31533. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31534. };
  31535. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31536. get: function () {
  31537. return this._masterMesh !== null && this._masterMesh !== undefined;
  31538. },
  31539. enumerable: true,
  31540. configurable: true
  31541. });
  31542. /**
  31543. * Determine if the current mesh is ready to be rendered
  31544. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31545. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31546. * @returns true if all associated assets are ready (material, textures, shaders)
  31547. */
  31548. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31549. if (completeCheck === void 0) { completeCheck = false; }
  31550. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31551. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31552. return false;
  31553. }
  31554. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31555. return false;
  31556. }
  31557. if (!this.subMeshes || this.subMeshes.length === 0) {
  31558. return true;
  31559. }
  31560. if (!completeCheck) {
  31561. return true;
  31562. }
  31563. var engine = this.getEngine();
  31564. var scene = this.getScene();
  31565. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31566. this.computeWorldMatrix();
  31567. var mat = this.material || scene.defaultMaterial;
  31568. if (mat) {
  31569. if (mat.storeEffectOnSubMeshes) {
  31570. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31571. var subMesh = _a[_i];
  31572. var effectiveMaterial = subMesh.getMaterial();
  31573. if (effectiveMaterial) {
  31574. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31575. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31576. return false;
  31577. }
  31578. }
  31579. else {
  31580. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31581. return false;
  31582. }
  31583. }
  31584. }
  31585. }
  31586. }
  31587. else {
  31588. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31589. return false;
  31590. }
  31591. }
  31592. }
  31593. // Shadows
  31594. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31595. var light = _c[_b];
  31596. var generator = light.getShadowGenerator();
  31597. if (generator) {
  31598. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31599. var subMesh = _e[_d];
  31600. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31601. return false;
  31602. }
  31603. }
  31604. }
  31605. }
  31606. // LOD
  31607. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31608. var lod = _g[_f];
  31609. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31610. return false;
  31611. }
  31612. }
  31613. return true;
  31614. };
  31615. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31616. /**
  31617. * 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.
  31618. */
  31619. get: function () {
  31620. return this._areNormalsFrozen;
  31621. },
  31622. enumerable: true,
  31623. configurable: true
  31624. });
  31625. /**
  31626. * 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.
  31627. * @returns the current mesh
  31628. */
  31629. Mesh.prototype.freezeNormals = function () {
  31630. this._areNormalsFrozen = true;
  31631. return this;
  31632. };
  31633. /**
  31634. * 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
  31635. * @returns the current mesh
  31636. */
  31637. Mesh.prototype.unfreezeNormals = function () {
  31638. this._areNormalsFrozen = false;
  31639. return this;
  31640. };
  31641. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31642. /**
  31643. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31644. */
  31645. set: function (count) {
  31646. this._overridenInstanceCount = count;
  31647. },
  31648. enumerable: true,
  31649. configurable: true
  31650. });
  31651. // Methods
  31652. /** @hidden */
  31653. Mesh.prototype._preActivate = function () {
  31654. var sceneRenderId = this.getScene().getRenderId();
  31655. if (this._preActivateId === sceneRenderId) {
  31656. return this;
  31657. }
  31658. this._preActivateId = sceneRenderId;
  31659. this._visibleInstances = null;
  31660. return this;
  31661. };
  31662. /** @hidden */
  31663. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31664. if (this._visibleInstances) {
  31665. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31666. }
  31667. return this;
  31668. };
  31669. /** @hidden */
  31670. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31671. if (!this._visibleInstances) {
  31672. this._visibleInstances = {};
  31673. this._visibleInstances.defaultRenderId = renderId;
  31674. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31675. }
  31676. if (!this._visibleInstances[renderId]) {
  31677. this._visibleInstances[renderId] = new Array();
  31678. }
  31679. this._visibleInstances[renderId].push(instance);
  31680. return this;
  31681. };
  31682. /**
  31683. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31684. * This means the mesh underlying bounding box and sphere are recomputed.
  31685. * @returns the current mesh
  31686. */
  31687. Mesh.prototype.refreshBoundingInfo = function () {
  31688. return this._refreshBoundingInfo(false);
  31689. };
  31690. /** @hidden */
  31691. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31692. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31693. return this;
  31694. }
  31695. var data = this._getPositionData(applySkeleton);
  31696. if (data) {
  31697. var bias = this.geometry ? this.geometry.boundingBias : null;
  31698. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31699. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31700. }
  31701. if (this.subMeshes) {
  31702. for (var index = 0; index < this.subMeshes.length; index++) {
  31703. this.subMeshes[index].refreshBoundingInfo();
  31704. }
  31705. }
  31706. this._updateBoundingInfo();
  31707. return this;
  31708. };
  31709. Mesh.prototype._getPositionData = function (applySkeleton) {
  31710. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31711. if (data && applySkeleton && this.skeleton) {
  31712. data = BABYLON.Tools.Slice(data);
  31713. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31714. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31715. if (matricesWeightsData && matricesIndicesData) {
  31716. var needExtras = this.numBoneInfluencers > 4;
  31717. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31718. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31719. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31720. var tempVector = BABYLON.Tmp.Vector3[0];
  31721. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31722. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31723. var matWeightIdx = 0;
  31724. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31725. finalMatrix.reset();
  31726. var inf;
  31727. var weight;
  31728. for (inf = 0; inf < 4; inf++) {
  31729. weight = matricesWeightsData[matWeightIdx + inf];
  31730. if (weight > 0) {
  31731. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31732. finalMatrix.addToSelf(tempMatrix);
  31733. }
  31734. }
  31735. if (needExtras) {
  31736. for (inf = 0; inf < 4; inf++) {
  31737. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31738. if (weight > 0) {
  31739. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31740. finalMatrix.addToSelf(tempMatrix);
  31741. }
  31742. }
  31743. }
  31744. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31745. tempVector.toArray(data, index);
  31746. }
  31747. }
  31748. }
  31749. return data;
  31750. };
  31751. /** @hidden */
  31752. Mesh.prototype._createGlobalSubMesh = function (force) {
  31753. var totalVertices = this.getTotalVertices();
  31754. if (!totalVertices || !this.getIndices()) {
  31755. return null;
  31756. }
  31757. // Check if we need to recreate the submeshes
  31758. if (this.subMeshes && this.subMeshes.length > 0) {
  31759. var ib = this.getIndices();
  31760. if (!ib) {
  31761. return null;
  31762. }
  31763. var totalIndices = ib.length;
  31764. var needToRecreate = false;
  31765. if (force) {
  31766. needToRecreate = true;
  31767. }
  31768. else {
  31769. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31770. var submesh = _a[_i];
  31771. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31772. needToRecreate = true;
  31773. break;
  31774. }
  31775. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31776. needToRecreate = true;
  31777. break;
  31778. }
  31779. }
  31780. }
  31781. if (!needToRecreate) {
  31782. return this.subMeshes[0];
  31783. }
  31784. }
  31785. this.releaseSubMeshes();
  31786. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31787. };
  31788. /**
  31789. * This function will subdivide the mesh into multiple submeshes
  31790. * @param count defines the expected number of submeshes
  31791. */
  31792. Mesh.prototype.subdivide = function (count) {
  31793. if (count < 1) {
  31794. return;
  31795. }
  31796. var totalIndices = this.getTotalIndices();
  31797. var subdivisionSize = (totalIndices / count) | 0;
  31798. var offset = 0;
  31799. // Ensure that subdivisionSize is a multiple of 3
  31800. while (subdivisionSize % 3 !== 0) {
  31801. subdivisionSize++;
  31802. }
  31803. this.releaseSubMeshes();
  31804. for (var index = 0; index < count; index++) {
  31805. if (offset >= totalIndices) {
  31806. break;
  31807. }
  31808. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31809. offset += subdivisionSize;
  31810. }
  31811. this.synchronizeInstances();
  31812. };
  31813. /**
  31814. * Copy a FloatArray into a specific associated vertex buffer
  31815. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31816. * - BABYLON.VertexBuffer.PositionKind
  31817. * - BABYLON.VertexBuffer.UVKind
  31818. * - BABYLON.VertexBuffer.UV2Kind
  31819. * - BABYLON.VertexBuffer.UV3Kind
  31820. * - BABYLON.VertexBuffer.UV4Kind
  31821. * - BABYLON.VertexBuffer.UV5Kind
  31822. * - BABYLON.VertexBuffer.UV6Kind
  31823. * - BABYLON.VertexBuffer.ColorKind
  31824. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31825. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31826. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31827. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31828. * @param data defines the data source
  31829. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31830. * @param stride defines the data stride size (can be null)
  31831. * @returns the current mesh
  31832. */
  31833. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31834. if (updatable === void 0) { updatable = false; }
  31835. if (!this._geometry) {
  31836. var vertexData = new BABYLON.VertexData();
  31837. vertexData.set(data, kind);
  31838. var scene = this.getScene();
  31839. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31840. }
  31841. else {
  31842. this._geometry.setVerticesData(kind, data, updatable, stride);
  31843. }
  31844. return this;
  31845. };
  31846. /**
  31847. * Flags an associated vertex buffer as updatable
  31848. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31849. * - BABYLON.VertexBuffer.PositionKind
  31850. * - BABYLON.VertexBuffer.UVKind
  31851. * - BABYLON.VertexBuffer.UV2Kind
  31852. * - BABYLON.VertexBuffer.UV3Kind
  31853. * - BABYLON.VertexBuffer.UV4Kind
  31854. * - BABYLON.VertexBuffer.UV5Kind
  31855. * - BABYLON.VertexBuffer.UV6Kind
  31856. * - BABYLON.VertexBuffer.ColorKind
  31857. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31858. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31859. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31860. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31861. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31862. */
  31863. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31864. if (updatable === void 0) { updatable = true; }
  31865. var vb = this.getVertexBuffer(kind);
  31866. if (!vb || vb.isUpdatable() === updatable) {
  31867. return;
  31868. }
  31869. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31870. };
  31871. /**
  31872. * Sets the mesh global Vertex Buffer
  31873. * @param buffer defines the buffer to use
  31874. * @returns the current mesh
  31875. */
  31876. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31877. if (!this._geometry) {
  31878. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31879. }
  31880. this._geometry.setVerticesBuffer(buffer);
  31881. return this;
  31882. };
  31883. /**
  31884. * Update a specific associated vertex buffer
  31885. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31886. * - BABYLON.VertexBuffer.PositionKind
  31887. * - BABYLON.VertexBuffer.UVKind
  31888. * - BABYLON.VertexBuffer.UV2Kind
  31889. * - BABYLON.VertexBuffer.UV3Kind
  31890. * - BABYLON.VertexBuffer.UV4Kind
  31891. * - BABYLON.VertexBuffer.UV5Kind
  31892. * - BABYLON.VertexBuffer.UV6Kind
  31893. * - BABYLON.VertexBuffer.ColorKind
  31894. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31895. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31896. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31897. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31898. * @param data defines the data source
  31899. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31900. * @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)
  31901. * @returns the current mesh
  31902. */
  31903. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31904. if (!this._geometry) {
  31905. return this;
  31906. }
  31907. if (!makeItUnique) {
  31908. this._geometry.updateVerticesData(kind, data, updateExtends);
  31909. }
  31910. else {
  31911. this.makeGeometryUnique();
  31912. this.updateVerticesData(kind, data, updateExtends, false);
  31913. }
  31914. return this;
  31915. };
  31916. /**
  31917. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31918. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31919. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31920. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31921. * @returns the current mesh
  31922. */
  31923. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31924. if (computeNormals === void 0) { computeNormals = true; }
  31925. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31926. if (!positions) {
  31927. return this;
  31928. }
  31929. positionFunction(positions);
  31930. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31931. if (computeNormals) {
  31932. var indices = this.getIndices();
  31933. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31934. if (!normals) {
  31935. return this;
  31936. }
  31937. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31938. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31939. }
  31940. return this;
  31941. };
  31942. /**
  31943. * Creates a un-shared specific occurence of the geometry for the mesh.
  31944. * @returns the current mesh
  31945. */
  31946. Mesh.prototype.makeGeometryUnique = function () {
  31947. if (!this._geometry) {
  31948. return this;
  31949. }
  31950. var oldGeometry = this._geometry;
  31951. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31952. oldGeometry.releaseForMesh(this, true);
  31953. geometry.applyToMesh(this);
  31954. return this;
  31955. };
  31956. /**
  31957. * Set the index buffer of this mesh
  31958. * @param indices defines the source data
  31959. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31960. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31961. * @returns the current mesh
  31962. */
  31963. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31964. if (totalVertices === void 0) { totalVertices = null; }
  31965. if (updatable === void 0) { updatable = false; }
  31966. if (!this._geometry) {
  31967. var vertexData = new BABYLON.VertexData();
  31968. vertexData.indices = indices;
  31969. var scene = this.getScene();
  31970. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31971. }
  31972. else {
  31973. this._geometry.setIndices(indices, totalVertices, updatable);
  31974. }
  31975. return this;
  31976. };
  31977. /**
  31978. * Update the current index buffer
  31979. * @param indices defines the source data
  31980. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31981. * @returns the current mesh
  31982. */
  31983. Mesh.prototype.updateIndices = function (indices, offset) {
  31984. if (!this._geometry) {
  31985. return this;
  31986. }
  31987. this._geometry.updateIndices(indices, offset);
  31988. return this;
  31989. };
  31990. /**
  31991. * Invert the geometry to move from a right handed system to a left handed one.
  31992. * @returns the current mesh
  31993. */
  31994. Mesh.prototype.toLeftHanded = function () {
  31995. if (!this._geometry) {
  31996. return this;
  31997. }
  31998. this._geometry.toLeftHanded();
  31999. return this;
  32000. };
  32001. /** @hidden */
  32002. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32003. if (!this._geometry) {
  32004. return this;
  32005. }
  32006. var engine = this.getScene().getEngine();
  32007. // Wireframe
  32008. var indexToBind;
  32009. if (this._unIndexed) {
  32010. indexToBind = null;
  32011. }
  32012. else {
  32013. switch (fillMode) {
  32014. case BABYLON.Material.PointFillMode:
  32015. indexToBind = null;
  32016. break;
  32017. case BABYLON.Material.WireFrameFillMode:
  32018. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32019. break;
  32020. default:
  32021. case BABYLON.Material.TriangleFillMode:
  32022. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32023. break;
  32024. }
  32025. }
  32026. // VBOs
  32027. this._geometry._bind(effect, indexToBind);
  32028. return this;
  32029. };
  32030. /** @hidden */
  32031. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32032. if (alternate === void 0) { alternate = false; }
  32033. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32034. return this;
  32035. }
  32036. if (this._onBeforeDrawObservable) {
  32037. this._onBeforeDrawObservable.notifyObservers(this);
  32038. }
  32039. var scene = this.getScene();
  32040. var engine = scene.getEngine();
  32041. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32042. // or triangles as points
  32043. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32044. }
  32045. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32046. // Triangles as wireframe
  32047. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32048. }
  32049. else {
  32050. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32051. }
  32052. if (scene._isAlternateRenderingEnabled && !alternate) {
  32053. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32054. if (!effect || !scene.activeCamera) {
  32055. return this;
  32056. }
  32057. scene._switchToAlternateCameraConfiguration(true);
  32058. this._effectiveMaterial.bindView(effect);
  32059. this._effectiveMaterial.bindViewProjection(effect);
  32060. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32061. this._draw(subMesh, fillMode, instancesCount, true);
  32062. engine.setViewport(scene.activeCamera.viewport);
  32063. scene._switchToAlternateCameraConfiguration(false);
  32064. this._effectiveMaterial.bindView(effect);
  32065. this._effectiveMaterial.bindViewProjection(effect);
  32066. }
  32067. return this;
  32068. };
  32069. /**
  32070. * Registers for this mesh a javascript function called just before the rendering process
  32071. * @param func defines the function to call before rendering this mesh
  32072. * @returns the current mesh
  32073. */
  32074. Mesh.prototype.registerBeforeRender = function (func) {
  32075. this.onBeforeRenderObservable.add(func);
  32076. return this;
  32077. };
  32078. /**
  32079. * Disposes a previously registered javascript function called before the rendering
  32080. * @param func defines the function to remove
  32081. * @returns the current mesh
  32082. */
  32083. Mesh.prototype.unregisterBeforeRender = function (func) {
  32084. this.onBeforeRenderObservable.removeCallback(func);
  32085. return this;
  32086. };
  32087. /**
  32088. * Registers for this mesh a javascript function called just after the rendering is complete
  32089. * @param func defines the function to call after rendering this mesh
  32090. * @returns the current mesh
  32091. */
  32092. Mesh.prototype.registerAfterRender = function (func) {
  32093. this.onAfterRenderObservable.add(func);
  32094. return this;
  32095. };
  32096. /**
  32097. * Disposes a previously registered javascript function called after the rendering.
  32098. * @param func defines the function to remove
  32099. * @returns the current mesh
  32100. */
  32101. Mesh.prototype.unregisterAfterRender = function (func) {
  32102. this.onAfterRenderObservable.removeCallback(func);
  32103. return this;
  32104. };
  32105. /** @hidden */
  32106. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32107. var scene = this.getScene();
  32108. this._batchCache.mustReturn = false;
  32109. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32110. this._batchCache.visibleInstances[subMeshId] = null;
  32111. if (this._visibleInstances) {
  32112. var currentRenderId = scene.getRenderId();
  32113. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32114. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32115. var selfRenderId = this._renderId;
  32116. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32117. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32118. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32119. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32120. }
  32121. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32122. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32123. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32124. this._batchCache.mustReturn = true;
  32125. return this._batchCache;
  32126. }
  32127. if (currentRenderId !== selfRenderId) {
  32128. this._batchCache.renderSelf[subMeshId] = false;
  32129. }
  32130. }
  32131. this._renderIdForInstances[subMeshId] = currentRenderId;
  32132. }
  32133. return this._batchCache;
  32134. };
  32135. /** @hidden */
  32136. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32137. var visibleInstances = batch.visibleInstances[subMesh._id];
  32138. if (!visibleInstances) {
  32139. return this;
  32140. }
  32141. var matricesCount = visibleInstances.length + 1;
  32142. var bufferSize = matricesCount * 16 * 4;
  32143. var currentInstancesBufferSize = this._instancesBufferSize;
  32144. var instancesBuffer = this._instancesBuffer;
  32145. while (this._instancesBufferSize < bufferSize) {
  32146. this._instancesBufferSize *= 2;
  32147. }
  32148. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32149. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32150. }
  32151. var offset = 0;
  32152. var instancesCount = 0;
  32153. var world = this.getWorldMatrix();
  32154. if (batch.renderSelf[subMesh._id]) {
  32155. world.copyToArray(this._instancesData, offset);
  32156. offset += 16;
  32157. instancesCount++;
  32158. }
  32159. if (visibleInstances) {
  32160. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32161. var instance = visibleInstances[instanceIndex];
  32162. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32163. offset += 16;
  32164. instancesCount++;
  32165. }
  32166. }
  32167. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32168. if (instancesBuffer) {
  32169. instancesBuffer.dispose();
  32170. }
  32171. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32172. this._instancesBuffer = instancesBuffer;
  32173. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32174. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32175. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32176. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32177. }
  32178. else {
  32179. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32180. }
  32181. this._bind(subMesh, effect, fillMode);
  32182. this._draw(subMesh, fillMode, instancesCount);
  32183. engine.unbindInstanceAttributes();
  32184. return this;
  32185. };
  32186. /** @hidden */
  32187. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32188. var scene = this.getScene();
  32189. var engine = scene.getEngine();
  32190. if (hardwareInstancedRendering) {
  32191. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32192. }
  32193. else {
  32194. if (batch.renderSelf[subMesh._id]) {
  32195. // Draw
  32196. if (onBeforeDraw) {
  32197. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32198. }
  32199. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32200. }
  32201. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32202. if (visibleInstancesForSubMesh) {
  32203. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32204. var instance = visibleInstancesForSubMesh[instanceIndex];
  32205. // World
  32206. var world = instance.getWorldMatrix();
  32207. if (onBeforeDraw) {
  32208. onBeforeDraw(true, world, effectiveMaterial);
  32209. }
  32210. // Draw
  32211. this._draw(subMesh, fillMode);
  32212. }
  32213. }
  32214. }
  32215. return this;
  32216. };
  32217. /**
  32218. * 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
  32219. * @param subMesh defines the subMesh to render
  32220. * @param enableAlphaMode defines if alpha mode can be changed
  32221. * @returns the current mesh
  32222. */
  32223. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32224. this._checkOcclusionQuery();
  32225. if (this._isOccluded) {
  32226. return this;
  32227. }
  32228. var scene = this.getScene();
  32229. // Managing instances
  32230. var batch = this._getInstancesRenderList(subMesh._id);
  32231. if (batch.mustReturn) {
  32232. return this;
  32233. }
  32234. // Checking geometry state
  32235. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32236. return this;
  32237. }
  32238. if (this._onBeforeRenderObservable) {
  32239. this._onBeforeRenderObservable.notifyObservers(this);
  32240. }
  32241. var engine = scene.getEngine();
  32242. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32243. // Material
  32244. var material = subMesh.getMaterial();
  32245. if (!material) {
  32246. return this;
  32247. }
  32248. this._effectiveMaterial = material;
  32249. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32250. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32251. return this;
  32252. }
  32253. }
  32254. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32255. return this;
  32256. }
  32257. // Alpha mode
  32258. if (enableAlphaMode) {
  32259. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32260. }
  32261. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32262. var step = _a[_i];
  32263. step.action(this, subMesh, batch);
  32264. }
  32265. var effect;
  32266. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32267. effect = subMesh.effect;
  32268. }
  32269. else {
  32270. effect = this._effectiveMaterial.getEffect();
  32271. }
  32272. if (!effect) {
  32273. return this;
  32274. }
  32275. var sideOrientation = this.overrideMaterialSideOrientation;
  32276. if (sideOrientation == null) {
  32277. sideOrientation = this._effectiveMaterial.sideOrientation;
  32278. if (this._getWorldMatrixDeterminant() < 0) {
  32279. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32280. }
  32281. }
  32282. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32283. if (this._effectiveMaterial.forceDepthWrite) {
  32284. engine.setDepthWrite(true);
  32285. }
  32286. // Bind
  32287. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32288. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32289. this._bind(subMesh, effect, fillMode);
  32290. }
  32291. var world = this.getWorldMatrix();
  32292. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32293. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32294. }
  32295. else {
  32296. this._effectiveMaterial.bind(world, this);
  32297. }
  32298. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32299. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32300. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32301. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32302. }
  32303. // Draw
  32304. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32305. // Unbind
  32306. this._effectiveMaterial.unbind();
  32307. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32308. var step = _c[_b];
  32309. step.action(this, subMesh, batch);
  32310. }
  32311. if (this._onAfterRenderObservable) {
  32312. this._onAfterRenderObservable.notifyObservers(this);
  32313. }
  32314. return this;
  32315. };
  32316. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32317. if (isInstance && effectiveMaterial) {
  32318. effectiveMaterial.bindOnlyWorldMatrix(world);
  32319. }
  32320. };
  32321. /**
  32322. * Normalize matrix weights so that all vertices have a total weight set to 1
  32323. */
  32324. Mesh.prototype.cleanMatrixWeights = function () {
  32325. var epsilon = 1e-3;
  32326. var noInfluenceBoneIndex = 0.0;
  32327. if (this.skeleton) {
  32328. noInfluenceBoneIndex = this.skeleton.bones.length;
  32329. }
  32330. else {
  32331. return;
  32332. }
  32333. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32334. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32335. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32336. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32337. var influencers = this.numBoneInfluencers;
  32338. var size = matricesWeights.length;
  32339. for (var i = 0; i < size; i += 4) {
  32340. var weight = 0.0;
  32341. var firstZeroWeight = -1;
  32342. for (var j = 0; j < 4; j++) {
  32343. var w = matricesWeights[i + j];
  32344. weight += w;
  32345. if (w < epsilon && firstZeroWeight < 0) {
  32346. firstZeroWeight = j;
  32347. }
  32348. }
  32349. if (matricesWeightsExtra) {
  32350. for (var j = 0; j < 4; j++) {
  32351. var w = matricesWeightsExtra[i + j];
  32352. weight += w;
  32353. if (w < epsilon && firstZeroWeight < 0) {
  32354. firstZeroWeight = j + 4;
  32355. }
  32356. }
  32357. }
  32358. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32359. firstZeroWeight = influencers - 1;
  32360. }
  32361. if (weight > epsilon) {
  32362. var mweight = 1.0 / weight;
  32363. for (var j = 0; j < 4; j++) {
  32364. matricesWeights[i + j] *= mweight;
  32365. }
  32366. if (matricesWeightsExtra) {
  32367. for (var j = 0; j < 4; j++) {
  32368. matricesWeightsExtra[i + j] *= mweight;
  32369. }
  32370. }
  32371. }
  32372. else {
  32373. if (firstZeroWeight >= 4) {
  32374. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32375. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32376. }
  32377. else {
  32378. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32379. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32380. }
  32381. }
  32382. }
  32383. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32384. if (matricesIndicesExtra) {
  32385. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32386. }
  32387. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32388. if (matricesWeightsExtra) {
  32389. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32390. }
  32391. };
  32392. /** @hidden */
  32393. Mesh.prototype._checkDelayState = function () {
  32394. var scene = this.getScene();
  32395. if (this._geometry) {
  32396. this._geometry.load(scene);
  32397. }
  32398. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32400. this._queueLoad(scene);
  32401. }
  32402. return this;
  32403. };
  32404. Mesh.prototype._queueLoad = function (scene) {
  32405. var _this = this;
  32406. scene._addPendingData(this);
  32407. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32408. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32409. if (data instanceof ArrayBuffer) {
  32410. _this._delayLoadingFunction(data, _this);
  32411. }
  32412. else {
  32413. _this._delayLoadingFunction(JSON.parse(data), _this);
  32414. }
  32415. _this.instances.forEach(function (instance) {
  32416. instance._syncSubMeshes();
  32417. });
  32418. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32419. scene._removePendingData(_this);
  32420. }, function () { }, scene.database, getBinaryData);
  32421. return this;
  32422. };
  32423. /**
  32424. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32425. * A mesh is in the frustum if its bounding box intersects the frustum
  32426. * @param frustumPlanes defines the frustum to test
  32427. * @returns true if the mesh is in the frustum planes
  32428. */
  32429. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32430. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32431. return false;
  32432. }
  32433. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32434. return false;
  32435. }
  32436. this._checkDelayState();
  32437. return true;
  32438. };
  32439. /**
  32440. * Sets the mesh material by the material or multiMaterial `id` property
  32441. * @param id is a string identifying the material or the multiMaterial
  32442. * @returns the current mesh
  32443. */
  32444. Mesh.prototype.setMaterialByID = function (id) {
  32445. var materials = this.getScene().materials;
  32446. var index;
  32447. for (index = materials.length - 1; index > -1; index--) {
  32448. if (materials[index].id === id) {
  32449. this.material = materials[index];
  32450. return this;
  32451. }
  32452. }
  32453. // Multi
  32454. var multiMaterials = this.getScene().multiMaterials;
  32455. for (index = multiMaterials.length - 1; index > -1; index--) {
  32456. if (multiMaterials[index].id === id) {
  32457. this.material = multiMaterials[index];
  32458. return this;
  32459. }
  32460. }
  32461. return this;
  32462. };
  32463. /**
  32464. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32465. * @returns an array of IAnimatable
  32466. */
  32467. Mesh.prototype.getAnimatables = function () {
  32468. var results = new Array();
  32469. if (this.material) {
  32470. results.push(this.material);
  32471. }
  32472. if (this.skeleton) {
  32473. results.push(this.skeleton);
  32474. }
  32475. return results;
  32476. };
  32477. /**
  32478. * Modifies the mesh geometry according to the passed transformation matrix.
  32479. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32480. * The mesh normals are modified using the same transformation.
  32481. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32482. * @param transform defines the transform matrix to use
  32483. * @see http://doc.babylonjs.com/resources/baking_transformations
  32484. * @returns the current mesh
  32485. */
  32486. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32487. // Position
  32488. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32489. return this;
  32490. }
  32491. var submeshes = this.subMeshes.splice(0);
  32492. this._resetPointsArrayCache();
  32493. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32494. var temp = new Array();
  32495. var index;
  32496. for (index = 0; index < data.length; index += 3) {
  32497. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32498. }
  32499. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32500. // Normals
  32501. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32502. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32503. temp = [];
  32504. for (index = 0; index < data.length; index += 3) {
  32505. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32506. }
  32507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32508. }
  32509. // flip faces?
  32510. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32511. this.flipFaces();
  32512. }
  32513. // Restore submeshes
  32514. this.releaseSubMeshes();
  32515. this.subMeshes = submeshes;
  32516. return this;
  32517. };
  32518. /**
  32519. * Modifies the mesh geometry according to its own current World Matrix.
  32520. * The mesh World Matrix is then reset.
  32521. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32522. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32523. * @see http://doc.babylonjs.com/resources/baking_transformations
  32524. * @returns the current mesh
  32525. */
  32526. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32527. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32528. this.scaling.copyFromFloats(1, 1, 1);
  32529. this.position.copyFromFloats(0, 0, 0);
  32530. this.rotation.copyFromFloats(0, 0, 0);
  32531. //only if quaternion is already set
  32532. if (this.rotationQuaternion) {
  32533. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32534. }
  32535. this._worldMatrix = BABYLON.Matrix.Identity();
  32536. return this;
  32537. };
  32538. Object.defineProperty(Mesh.prototype, "_positions", {
  32539. // Cache
  32540. /** @hidden */
  32541. get: function () {
  32542. if (this._geometry) {
  32543. return this._geometry._positions;
  32544. }
  32545. return null;
  32546. },
  32547. enumerable: true,
  32548. configurable: true
  32549. });
  32550. /** @hidden */
  32551. Mesh.prototype._resetPointsArrayCache = function () {
  32552. if (this._geometry) {
  32553. this._geometry._resetPointsArrayCache();
  32554. }
  32555. return this;
  32556. };
  32557. /** @hidden */
  32558. Mesh.prototype._generatePointsArray = function () {
  32559. if (this._geometry) {
  32560. return this._geometry._generatePointsArray();
  32561. }
  32562. return false;
  32563. };
  32564. /**
  32565. * Returns a new Mesh object generated from the current mesh properties.
  32566. * This method must not get confused with createInstance()
  32567. * @param name is a string, the name given to the new mesh
  32568. * @param newParent can be any Node object (default `null`)
  32569. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32570. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32571. * @returns a new mesh
  32572. */
  32573. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32574. if (name === void 0) { name = ""; }
  32575. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32576. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32577. };
  32578. /**
  32579. * Releases resources associated with this mesh.
  32580. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32581. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32582. */
  32583. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32584. var _this = this;
  32585. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32586. this.morphTargetManager = null;
  32587. if (this._geometry) {
  32588. this._geometry.releaseForMesh(this, true);
  32589. }
  32590. if (this._onBeforeDrawObservable) {
  32591. this._onBeforeDrawObservable.clear();
  32592. }
  32593. if (this._onBeforeRenderObservable) {
  32594. this._onBeforeRenderObservable.clear();
  32595. }
  32596. if (this._onAfterRenderObservable) {
  32597. this._onAfterRenderObservable.clear();
  32598. }
  32599. // Sources
  32600. var meshes = this.getScene().meshes;
  32601. meshes.forEach(function (abstractMesh) {
  32602. var mesh = abstractMesh;
  32603. if (mesh._source && mesh._source === _this) {
  32604. mesh._source = null;
  32605. }
  32606. });
  32607. this._source = null;
  32608. // Instances
  32609. if (this._instancesBuffer) {
  32610. this._instancesBuffer.dispose();
  32611. this._instancesBuffer = null;
  32612. }
  32613. while (this.instances.length) {
  32614. this.instances[0].dispose();
  32615. }
  32616. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32617. };
  32618. /**
  32619. * Modifies the mesh geometry according to a displacement map.
  32620. * 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.
  32621. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32622. * @param url is a string, the URL from the image file is to be downloaded.
  32623. * @param minHeight is the lower limit of the displacement.
  32624. * @param maxHeight is the upper limit of the displacement.
  32625. * @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.
  32626. * @param uvOffset is an optional vector2 used to offset UV.
  32627. * @param uvScale is an optional vector2 used to scale UV.
  32628. * @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.
  32629. * @returns the Mesh.
  32630. */
  32631. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32632. var _this = this;
  32633. if (forceUpdate === void 0) { forceUpdate = false; }
  32634. var scene = this.getScene();
  32635. var onload = function (img) {
  32636. // Getting height map data
  32637. var canvas = document.createElement("canvas");
  32638. var context = canvas.getContext("2d");
  32639. var heightMapWidth = img.width;
  32640. var heightMapHeight = img.height;
  32641. canvas.width = heightMapWidth;
  32642. canvas.height = heightMapHeight;
  32643. context.drawImage(img, 0, 0);
  32644. // Create VertexData from map data
  32645. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32646. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32647. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32648. //execute success callback, if set
  32649. if (onSuccess) {
  32650. onSuccess(_this);
  32651. }
  32652. };
  32653. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32654. return this;
  32655. };
  32656. /**
  32657. * Modifies the mesh geometry according to a displacementMap buffer.
  32658. * 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.
  32659. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32660. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32661. * @param heightMapWidth is the width of the buffer image.
  32662. * @param heightMapHeight is the height of the buffer image.
  32663. * @param minHeight is the lower limit of the displacement.
  32664. * @param maxHeight is the upper limit of the displacement.
  32665. * @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.
  32666. * @param uvOffset is an optional vector2 used to offset UV.
  32667. * @param uvScale is an optional vector2 used to scale UV.
  32668. * @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.
  32669. * @returns the Mesh.
  32670. */
  32671. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32672. if (forceUpdate === void 0) { forceUpdate = false; }
  32673. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32674. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32675. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32676. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32677. return this;
  32678. }
  32679. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32680. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32681. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32682. var position = BABYLON.Vector3.Zero();
  32683. var normal = BABYLON.Vector3.Zero();
  32684. var uv = BABYLON.Vector2.Zero();
  32685. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32686. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32687. for (var index = 0; index < positions.length; index += 3) {
  32688. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32689. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32690. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32691. // Compute height
  32692. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32693. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32694. var pos = (u + v * heightMapWidth) * 4;
  32695. var r = buffer[pos] / 255.0;
  32696. var g = buffer[pos + 1] / 255.0;
  32697. var b = buffer[pos + 2] / 255.0;
  32698. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32699. normal.normalize();
  32700. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32701. position = position.add(normal);
  32702. position.toArray(positions, index);
  32703. }
  32704. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32705. if (forceUpdate) {
  32706. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32707. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32708. }
  32709. else {
  32710. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32711. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32712. }
  32713. return this;
  32714. };
  32715. /**
  32716. * Modify the mesh to get a flat shading rendering.
  32717. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32718. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32719. * @returns current mesh
  32720. */
  32721. Mesh.prototype.convertToFlatShadedMesh = function () {
  32722. var kinds = this.getVerticesDataKinds();
  32723. var vbs = {};
  32724. var data = {};
  32725. var newdata = {};
  32726. var updatableNormals = false;
  32727. var kindIndex;
  32728. var kind;
  32729. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32730. kind = kinds[kindIndex];
  32731. var vertexBuffer = this.getVertexBuffer(kind);
  32732. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32733. updatableNormals = vertexBuffer.isUpdatable();
  32734. kinds.splice(kindIndex, 1);
  32735. kindIndex--;
  32736. continue;
  32737. }
  32738. vbs[kind] = vertexBuffer;
  32739. data[kind] = vbs[kind].getData();
  32740. newdata[kind] = [];
  32741. }
  32742. // Save previous submeshes
  32743. var previousSubmeshes = this.subMeshes.slice(0);
  32744. var indices = this.getIndices();
  32745. var totalIndices = this.getTotalIndices();
  32746. // Generating unique vertices per face
  32747. var index;
  32748. for (index = 0; index < totalIndices; index++) {
  32749. var vertexIndex = indices[index];
  32750. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32751. kind = kinds[kindIndex];
  32752. var stride = vbs[kind].getStrideSize();
  32753. for (var offset = 0; offset < stride; offset++) {
  32754. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32755. }
  32756. }
  32757. }
  32758. // Updating faces & normal
  32759. var normals = [];
  32760. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32761. for (index = 0; index < totalIndices; index += 3) {
  32762. indices[index] = index;
  32763. indices[index + 1] = index + 1;
  32764. indices[index + 2] = index + 2;
  32765. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32766. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32767. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32768. var p1p2 = p1.subtract(p2);
  32769. var p3p2 = p3.subtract(p2);
  32770. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32771. // Store same normals for every vertex
  32772. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32773. normals.push(normal.x);
  32774. normals.push(normal.y);
  32775. normals.push(normal.z);
  32776. }
  32777. }
  32778. this.setIndices(indices);
  32779. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32780. // Updating vertex buffers
  32781. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32782. kind = kinds[kindIndex];
  32783. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32784. }
  32785. // Updating submeshes
  32786. this.releaseSubMeshes();
  32787. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32788. var previousOne = previousSubmeshes[submeshIndex];
  32789. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32790. }
  32791. this.synchronizeInstances();
  32792. return this;
  32793. };
  32794. /**
  32795. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32796. * In other words, more vertices, no more indices and a single bigger VBO.
  32797. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32798. * @returns current mesh
  32799. */
  32800. Mesh.prototype.convertToUnIndexedMesh = function () {
  32801. var kinds = this.getVerticesDataKinds();
  32802. var vbs = {};
  32803. var data = {};
  32804. var newdata = {};
  32805. var kindIndex;
  32806. var kind;
  32807. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32808. kind = kinds[kindIndex];
  32809. var vertexBuffer = this.getVertexBuffer(kind);
  32810. vbs[kind] = vertexBuffer;
  32811. data[kind] = vbs[kind].getData();
  32812. newdata[kind] = [];
  32813. }
  32814. // Save previous submeshes
  32815. var previousSubmeshes = this.subMeshes.slice(0);
  32816. var indices = this.getIndices();
  32817. var totalIndices = this.getTotalIndices();
  32818. // Generating unique vertices per face
  32819. var index;
  32820. for (index = 0; index < totalIndices; index++) {
  32821. var vertexIndex = indices[index];
  32822. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32823. kind = kinds[kindIndex];
  32824. var stride = vbs[kind].getStrideSize();
  32825. for (var offset = 0; offset < stride; offset++) {
  32826. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32827. }
  32828. }
  32829. }
  32830. // Updating indices
  32831. for (index = 0; index < totalIndices; index += 3) {
  32832. indices[index] = index;
  32833. indices[index + 1] = index + 1;
  32834. indices[index + 2] = index + 2;
  32835. }
  32836. this.setIndices(indices);
  32837. // Updating vertex buffers
  32838. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32839. kind = kinds[kindIndex];
  32840. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32841. }
  32842. // Updating submeshes
  32843. this.releaseSubMeshes();
  32844. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32845. var previousOne = previousSubmeshes[submeshIndex];
  32846. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32847. }
  32848. this._unIndexed = true;
  32849. this.synchronizeInstances();
  32850. return this;
  32851. };
  32852. /**
  32853. * Inverses facet orientations.
  32854. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32855. * @param flipNormals will also inverts the normals
  32856. * @returns current mesh
  32857. */
  32858. Mesh.prototype.flipFaces = function (flipNormals) {
  32859. if (flipNormals === void 0) { flipNormals = false; }
  32860. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32861. var i;
  32862. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32863. for (i = 0; i < vertex_data.normals.length; i++) {
  32864. vertex_data.normals[i] *= -1;
  32865. }
  32866. }
  32867. if (vertex_data.indices) {
  32868. var temp;
  32869. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32870. // reassign indices
  32871. temp = vertex_data.indices[i + 1];
  32872. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32873. vertex_data.indices[i + 2] = temp;
  32874. }
  32875. }
  32876. vertex_data.applyToMesh(this);
  32877. return this;
  32878. };
  32879. // Instances
  32880. /**
  32881. * Creates a new InstancedMesh object from the mesh model.
  32882. * Warning : this method is not supported for Line mesh and LineSystem
  32883. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32884. * @param name defines the name of the new instance
  32885. * @returns a new InstancedMesh
  32886. */
  32887. Mesh.prototype.createInstance = function (name) {
  32888. return new BABYLON.InstancedMesh(name, this);
  32889. };
  32890. /**
  32891. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32892. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32893. * @returns the current mesh
  32894. */
  32895. Mesh.prototype.synchronizeInstances = function () {
  32896. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32897. var instance = this.instances[instanceIndex];
  32898. instance._syncSubMeshes();
  32899. }
  32900. return this;
  32901. };
  32902. /**
  32903. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32904. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32905. * This should be used together with the simplification to avoid disappearing triangles.
  32906. * @param successCallback an optional success callback to be called after the optimization finished.
  32907. * @returns the current mesh
  32908. */
  32909. Mesh.prototype.optimizeIndices = function (successCallback) {
  32910. var _this = this;
  32911. var indices = this.getIndices();
  32912. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32913. if (!positions || !indices) {
  32914. return this;
  32915. }
  32916. var vectorPositions = new Array();
  32917. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32918. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32919. }
  32920. var dupes = new Array();
  32921. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32922. var realPos = vectorPositions.length - 1 - iteration;
  32923. var testedPosition = vectorPositions[realPos];
  32924. for (var j = 0; j < realPos; ++j) {
  32925. var againstPosition = vectorPositions[j];
  32926. if (testedPosition.equals(againstPosition)) {
  32927. dupes[realPos] = j;
  32928. break;
  32929. }
  32930. }
  32931. }, function () {
  32932. for (var i = 0; i < indices.length; ++i) {
  32933. indices[i] = dupes[indices[i]] || indices[i];
  32934. }
  32935. //indices are now reordered
  32936. var originalSubMeshes = _this.subMeshes.slice(0);
  32937. _this.setIndices(indices);
  32938. _this.subMeshes = originalSubMeshes;
  32939. if (successCallback) {
  32940. successCallback(_this);
  32941. }
  32942. });
  32943. return this;
  32944. };
  32945. /**
  32946. * Serialize current mesh
  32947. * @param serializationObject defines the object which will receive the serialization data
  32948. */
  32949. Mesh.prototype.serialize = function (serializationObject) {
  32950. serializationObject.name = this.name;
  32951. serializationObject.id = this.id;
  32952. serializationObject.type = this.getClassName();
  32953. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32954. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32955. }
  32956. serializationObject.position = this.position.asArray();
  32957. if (this.rotationQuaternion) {
  32958. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32959. }
  32960. else if (this.rotation) {
  32961. serializationObject.rotation = this.rotation.asArray();
  32962. }
  32963. serializationObject.scaling = this.scaling.asArray();
  32964. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32965. serializationObject.isEnabled = this.isEnabled(false);
  32966. serializationObject.isVisible = this.isVisible;
  32967. serializationObject.infiniteDistance = this.infiniteDistance;
  32968. serializationObject.pickable = this.isPickable;
  32969. serializationObject.receiveShadows = this.receiveShadows;
  32970. serializationObject.billboardMode = this.billboardMode;
  32971. serializationObject.visibility = this.visibility;
  32972. serializationObject.checkCollisions = this.checkCollisions;
  32973. serializationObject.isBlocker = this.isBlocker;
  32974. // Parent
  32975. if (this.parent) {
  32976. serializationObject.parentId = this.parent.id;
  32977. }
  32978. // Geometry
  32979. serializationObject.isUnIndexed = this.isUnIndexed;
  32980. var geometry = this._geometry;
  32981. if (geometry) {
  32982. var geometryId = geometry.id;
  32983. serializationObject.geometryId = geometryId;
  32984. // SubMeshes
  32985. serializationObject.subMeshes = [];
  32986. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32987. var subMesh = this.subMeshes[subIndex];
  32988. serializationObject.subMeshes.push({
  32989. materialIndex: subMesh.materialIndex,
  32990. verticesStart: subMesh.verticesStart,
  32991. verticesCount: subMesh.verticesCount,
  32992. indexStart: subMesh.indexStart,
  32993. indexCount: subMesh.indexCount
  32994. });
  32995. }
  32996. }
  32997. // Material
  32998. if (this.material) {
  32999. serializationObject.materialId = this.material.id;
  33000. }
  33001. else {
  33002. this.material = null;
  33003. }
  33004. // Morph targets
  33005. if (this.morphTargetManager) {
  33006. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33007. }
  33008. // Skeleton
  33009. if (this.skeleton) {
  33010. serializationObject.skeletonId = this.skeleton.id;
  33011. }
  33012. // Physics
  33013. //TODO implement correct serialization for physics impostors.
  33014. var impostor = this.getPhysicsImpostor();
  33015. if (impostor) {
  33016. serializationObject.physicsMass = impostor.getParam("mass");
  33017. serializationObject.physicsFriction = impostor.getParam("friction");
  33018. serializationObject.physicsRestitution = impostor.getParam("mass");
  33019. serializationObject.physicsImpostor = impostor.type;
  33020. }
  33021. // Metadata
  33022. if (this.metadata) {
  33023. serializationObject.metadata = this.metadata;
  33024. }
  33025. // Instances
  33026. serializationObject.instances = [];
  33027. for (var index = 0; index < this.instances.length; index++) {
  33028. var instance = this.instances[index];
  33029. if (instance.doNotSerialize) {
  33030. continue;
  33031. }
  33032. var serializationInstance = {
  33033. name: instance.name,
  33034. id: instance.id,
  33035. position: instance.position.asArray(),
  33036. scaling: instance.scaling.asArray()
  33037. };
  33038. if (instance.parent) {
  33039. serializationInstance.parentId = instance.parent.id;
  33040. }
  33041. if (instance.rotationQuaternion) {
  33042. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33043. }
  33044. else if (instance.rotation) {
  33045. serializationInstance.rotation = instance.rotation.asArray();
  33046. }
  33047. serializationObject.instances.push(serializationInstance);
  33048. // Animations
  33049. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33050. serializationInstance.ranges = instance.serializeAnimationRanges();
  33051. }
  33052. //
  33053. // Animations
  33054. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33055. serializationObject.ranges = this.serializeAnimationRanges();
  33056. // Layer mask
  33057. serializationObject.layerMask = this.layerMask;
  33058. // Alpha
  33059. serializationObject.alphaIndex = this.alphaIndex;
  33060. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33061. // Overlay
  33062. serializationObject.overlayAlpha = this.overlayAlpha;
  33063. serializationObject.overlayColor = this.overlayColor.asArray();
  33064. serializationObject.renderOverlay = this.renderOverlay;
  33065. // Fog
  33066. serializationObject.applyFog = this.applyFog;
  33067. // Action Manager
  33068. if (this.actionManager) {
  33069. serializationObject.actions = this.actionManager.serialize(this.name);
  33070. }
  33071. };
  33072. /** @hidden */
  33073. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33074. if (!this.geometry) {
  33075. return;
  33076. }
  33077. this._markSubMeshesAsAttributesDirty();
  33078. var morphTargetManager = this._morphTargetManager;
  33079. if (morphTargetManager && morphTargetManager.vertexCount) {
  33080. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33081. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33082. this.morphTargetManager = null;
  33083. return;
  33084. }
  33085. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33086. var morphTarget = morphTargetManager.getActiveTarget(index);
  33087. var positions = morphTarget.getPositions();
  33088. if (!positions) {
  33089. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33090. return;
  33091. }
  33092. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33093. var normals = morphTarget.getNormals();
  33094. if (normals) {
  33095. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33096. }
  33097. var tangents = morphTarget.getTangents();
  33098. if (tangents) {
  33099. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33100. }
  33101. }
  33102. }
  33103. else {
  33104. var index = 0;
  33105. // Positions
  33106. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33107. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33108. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33109. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33110. }
  33111. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33112. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33113. }
  33114. index++;
  33115. }
  33116. }
  33117. };
  33118. // Statics
  33119. /**
  33120. * Returns a new Mesh object parsed from the source provided.
  33121. * @param parsedMesh is the source
  33122. * @param scene defines the hosting scene
  33123. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33124. * @returns a new Mesh
  33125. */
  33126. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33127. var mesh;
  33128. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33129. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33130. }
  33131. else {
  33132. mesh = new Mesh(parsedMesh.name, scene);
  33133. }
  33134. mesh.id = parsedMesh.id;
  33135. if (BABYLON.Tags) {
  33136. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33137. }
  33138. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33139. if (parsedMesh.metadata !== undefined) {
  33140. mesh.metadata = parsedMesh.metadata;
  33141. }
  33142. if (parsedMesh.rotationQuaternion) {
  33143. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33144. }
  33145. else if (parsedMesh.rotation) {
  33146. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33147. }
  33148. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33149. if (parsedMesh.localMatrix) {
  33150. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33151. }
  33152. else if (parsedMesh.pivotMatrix) {
  33153. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33154. }
  33155. mesh.setEnabled(parsedMesh.isEnabled);
  33156. mesh.isVisible = parsedMesh.isVisible;
  33157. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33158. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33159. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33160. if (parsedMesh.applyFog !== undefined) {
  33161. mesh.applyFog = parsedMesh.applyFog;
  33162. }
  33163. if (parsedMesh.pickable !== undefined) {
  33164. mesh.isPickable = parsedMesh.pickable;
  33165. }
  33166. if (parsedMesh.alphaIndex !== undefined) {
  33167. mesh.alphaIndex = parsedMesh.alphaIndex;
  33168. }
  33169. mesh.receiveShadows = parsedMesh.receiveShadows;
  33170. mesh.billboardMode = parsedMesh.billboardMode;
  33171. if (parsedMesh.visibility !== undefined) {
  33172. mesh.visibility = parsedMesh.visibility;
  33173. }
  33174. mesh.checkCollisions = parsedMesh.checkCollisions;
  33175. if (parsedMesh.isBlocker !== undefined) {
  33176. mesh.isBlocker = parsedMesh.isBlocker;
  33177. }
  33178. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33179. // freezeWorldMatrix
  33180. if (parsedMesh.freezeWorldMatrix) {
  33181. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33182. }
  33183. // Parent
  33184. if (parsedMesh.parentId) {
  33185. mesh._waitingParentId = parsedMesh.parentId;
  33186. }
  33187. // Actions
  33188. if (parsedMesh.actions !== undefined) {
  33189. mesh._waitingActions = parsedMesh.actions;
  33190. }
  33191. // Overlay
  33192. if (parsedMesh.overlayAlpha !== undefined) {
  33193. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33194. }
  33195. if (parsedMesh.overlayColor !== undefined) {
  33196. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33197. }
  33198. if (parsedMesh.renderOverlay !== undefined) {
  33199. mesh.renderOverlay = parsedMesh.renderOverlay;
  33200. }
  33201. // Geometry
  33202. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33203. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33204. if (parsedMesh.delayLoadingFile) {
  33205. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33206. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33207. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33208. if (parsedMesh._binaryInfo) {
  33209. mesh._binaryInfo = parsedMesh._binaryInfo;
  33210. }
  33211. mesh._delayInfo = [];
  33212. if (parsedMesh.hasUVs) {
  33213. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33214. }
  33215. if (parsedMesh.hasUVs2) {
  33216. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33217. }
  33218. if (parsedMesh.hasUVs3) {
  33219. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33220. }
  33221. if (parsedMesh.hasUVs4) {
  33222. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33223. }
  33224. if (parsedMesh.hasUVs5) {
  33225. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33226. }
  33227. if (parsedMesh.hasUVs6) {
  33228. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33229. }
  33230. if (parsedMesh.hasColors) {
  33231. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33232. }
  33233. if (parsedMesh.hasMatricesIndices) {
  33234. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33235. }
  33236. if (parsedMesh.hasMatricesWeights) {
  33237. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33238. }
  33239. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33240. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33241. mesh._checkDelayState();
  33242. }
  33243. }
  33244. else {
  33245. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33246. }
  33247. // Material
  33248. if (parsedMesh.materialId) {
  33249. mesh.setMaterialByID(parsedMesh.materialId);
  33250. }
  33251. else {
  33252. mesh.material = null;
  33253. }
  33254. // Morph targets
  33255. if (parsedMesh.morphTargetManagerId > -1) {
  33256. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33257. }
  33258. // Skeleton
  33259. if (parsedMesh.skeletonId > -1) {
  33260. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33261. if (parsedMesh.numBoneInfluencers) {
  33262. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33263. }
  33264. }
  33265. // Animations
  33266. if (parsedMesh.animations) {
  33267. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33268. var parsedAnimation = parsedMesh.animations[animationIndex];
  33269. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33270. }
  33271. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33272. }
  33273. if (parsedMesh.autoAnimate) {
  33274. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33275. }
  33276. // Layer Mask
  33277. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33278. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33279. }
  33280. else {
  33281. mesh.layerMask = 0x0FFFFFFF;
  33282. }
  33283. // Physics
  33284. if (parsedMesh.physicsImpostor) {
  33285. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33286. mass: parsedMesh.physicsMass,
  33287. friction: parsedMesh.physicsFriction,
  33288. restitution: parsedMesh.physicsRestitution
  33289. }, scene);
  33290. }
  33291. // Instances
  33292. if (parsedMesh.instances) {
  33293. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33294. var parsedInstance = parsedMesh.instances[index];
  33295. var instance = mesh.createInstance(parsedInstance.name);
  33296. if (parsedInstance.id) {
  33297. instance.id = parsedInstance.id;
  33298. }
  33299. if (BABYLON.Tags) {
  33300. if (parsedInstance.tags) {
  33301. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33302. }
  33303. else {
  33304. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33305. }
  33306. }
  33307. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33308. if (parsedInstance.parentId) {
  33309. instance._waitingParentId = parsedInstance.parentId;
  33310. }
  33311. if (parsedInstance.rotationQuaternion) {
  33312. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33313. }
  33314. else if (parsedInstance.rotation) {
  33315. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33316. }
  33317. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33318. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33319. instance.checkCollisions = parsedInstance.checkCollisions;
  33320. }
  33321. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33322. instance.isPickable = parsedInstance.pickable;
  33323. }
  33324. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33325. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33326. }
  33327. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33328. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33329. }
  33330. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33331. instance.alphaIndex = parsedInstance.alphaIndex;
  33332. }
  33333. // Physics
  33334. if (parsedInstance.physicsImpostor) {
  33335. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33336. mass: parsedInstance.physicsMass,
  33337. friction: parsedInstance.physicsFriction,
  33338. restitution: parsedInstance.physicsRestitution
  33339. }, scene);
  33340. }
  33341. // Animation
  33342. if (parsedInstance.animations) {
  33343. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33344. parsedAnimation = parsedInstance.animations[animationIndex];
  33345. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33346. }
  33347. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33348. if (parsedInstance.autoAnimate) {
  33349. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33350. }
  33351. }
  33352. }
  33353. }
  33354. return mesh;
  33355. };
  33356. /**
  33357. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33358. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33359. * @param name defines the name of the mesh to create
  33360. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33361. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33362. * @param closePath creates a seam between the first and the last points of each path of the path array
  33363. * @param offset is taken in account only if the `pathArray` is containing a single path
  33364. * @param scene defines the hosting scene
  33365. * @param updatable defines if the mesh must be flagged as updatable
  33366. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33367. * @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)
  33368. * @returns a new Mesh
  33369. */
  33370. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33371. if (closeArray === void 0) { closeArray = false; }
  33372. if (updatable === void 0) { updatable = false; }
  33373. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33374. pathArray: pathArray,
  33375. closeArray: closeArray,
  33376. closePath: closePath,
  33377. offset: offset,
  33378. updatable: updatable,
  33379. sideOrientation: sideOrientation,
  33380. instance: instance
  33381. }, scene);
  33382. };
  33383. /**
  33384. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33385. * @param name defines the name of the mesh to create
  33386. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33387. * @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
  33388. * @param scene defines the hosting scene
  33389. * @param updatable defines if the mesh must be flagged as updatable
  33390. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33391. * @returns a new Mesh
  33392. */
  33393. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33394. if (scene === void 0) { scene = null; }
  33395. var options = {
  33396. radius: radius,
  33397. tessellation: tessellation,
  33398. sideOrientation: sideOrientation,
  33399. updatable: updatable
  33400. };
  33401. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33402. };
  33403. /**
  33404. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33405. * @param name defines the name of the mesh to create
  33406. * @param size sets the size (float) of each box side (default 1)
  33407. * @param scene defines the hosting scene
  33408. * @param updatable defines if the mesh must be flagged as updatable
  33409. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33410. * @returns a new Mesh
  33411. */
  33412. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33413. if (scene === void 0) { scene = null; }
  33414. var options = {
  33415. size: size,
  33416. sideOrientation: sideOrientation,
  33417. updatable: updatable
  33418. };
  33419. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33420. };
  33421. /**
  33422. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33423. * @param name defines the name of the mesh to create
  33424. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33425. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33426. * @param scene defines the hosting scene
  33427. * @param updatable defines if the mesh must be flagged as updatable
  33428. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33429. * @returns a new Mesh
  33430. */
  33431. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33432. var options = {
  33433. segments: segments,
  33434. diameterX: diameter,
  33435. diameterY: diameter,
  33436. diameterZ: diameter,
  33437. sideOrientation: sideOrientation,
  33438. updatable: updatable
  33439. };
  33440. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33441. };
  33442. /**
  33443. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33444. * @param name defines the name of the mesh to create
  33445. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33446. * @param diameterTop set the top cap diameter (floats, default 1)
  33447. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33448. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33449. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33450. * @param scene defines the hosting scene
  33451. * @param updatable defines if the mesh must be flagged as updatable
  33452. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33453. * @returns a new Mesh
  33454. */
  33455. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33456. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33457. if (scene !== undefined) {
  33458. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33459. updatable = scene;
  33460. }
  33461. scene = subdivisions;
  33462. subdivisions = 1;
  33463. }
  33464. var options = {
  33465. height: height,
  33466. diameterTop: diameterTop,
  33467. diameterBottom: diameterBottom,
  33468. tessellation: tessellation,
  33469. subdivisions: subdivisions,
  33470. sideOrientation: sideOrientation,
  33471. updatable: updatable
  33472. };
  33473. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33474. };
  33475. // Torus (Code from SharpDX.org)
  33476. /**
  33477. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33478. * @param name defines the name of the mesh to create
  33479. * @param diameter sets the diameter size (float) of the torus (default 1)
  33480. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33481. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33482. * @param scene defines the hosting scene
  33483. * @param updatable defines if the mesh must be flagged as updatable
  33484. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33485. * @returns a new Mesh
  33486. */
  33487. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33488. var options = {
  33489. diameter: diameter,
  33490. thickness: thickness,
  33491. tessellation: tessellation,
  33492. sideOrientation: sideOrientation,
  33493. updatable: updatable
  33494. };
  33495. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33496. };
  33497. /**
  33498. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33499. * @param name defines the name of the mesh to create
  33500. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33501. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33502. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33503. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33504. * @param p the number of windings on X axis (positive integers, default 2)
  33505. * @param q the number of windings on Y axis (positive integers, default 3)
  33506. * @param scene defines the hosting scene
  33507. * @param updatable defines if the mesh must be flagged as updatable
  33508. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33509. * @returns a new Mesh
  33510. */
  33511. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33512. var options = {
  33513. radius: radius,
  33514. tube: tube,
  33515. radialSegments: radialSegments,
  33516. tubularSegments: tubularSegments,
  33517. p: p,
  33518. q: q,
  33519. sideOrientation: sideOrientation,
  33520. updatable: updatable
  33521. };
  33522. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33523. };
  33524. /**
  33525. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33526. * @param name defines the name of the mesh to create
  33527. * @param points is an array successive Vector3
  33528. * @param scene defines the hosting scene
  33529. * @param updatable defines if the mesh must be flagged as updatable
  33530. * @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).
  33531. * @returns a new Mesh
  33532. */
  33533. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33534. if (scene === void 0) { scene = null; }
  33535. if (updatable === void 0) { updatable = false; }
  33536. if (instance === void 0) { instance = null; }
  33537. var options = {
  33538. points: points,
  33539. updatable: updatable,
  33540. instance: instance
  33541. };
  33542. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33543. };
  33544. /**
  33545. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33546. * @param name defines the name of the mesh to create
  33547. * @param points is an array successive Vector3
  33548. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33549. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33550. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33551. * @param scene defines the hosting scene
  33552. * @param updatable defines if the mesh must be flagged as updatable
  33553. * @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)
  33554. * @returns a new Mesh
  33555. */
  33556. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33557. if (scene === void 0) { scene = null; }
  33558. var options = {
  33559. points: points,
  33560. dashSize: dashSize,
  33561. gapSize: gapSize,
  33562. dashNb: dashNb,
  33563. updatable: updatable,
  33564. instance: instance
  33565. };
  33566. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33567. };
  33568. /**
  33569. * Creates a polygon mesh.
  33570. * Please consider using the same method from the MeshBuilder class instead.
  33571. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33572. * 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.
  33573. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33574. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33575. * Remember you can only change the shape positions, not their number when updating a polygon.
  33576. */
  33577. /**
  33578. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33579. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33580. * @param name defines the name of the mesh to create
  33581. * @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
  33582. * @param scene defines the hosting scene
  33583. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33584. * @param updatable defines if the mesh must be flagged as updatable
  33585. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33586. * @returns a new Mesh
  33587. */
  33588. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33589. var options = {
  33590. shape: shape,
  33591. holes: holes,
  33592. updatable: updatable,
  33593. sideOrientation: sideOrientation
  33594. };
  33595. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33596. };
  33597. /**
  33598. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33599. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33600. * @param name defines the name of the mesh to create
  33601. * @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
  33602. * @param depth defines the height of extrusion
  33603. * @param scene defines the hosting scene
  33604. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33605. * @param updatable defines if the mesh must be flagged as updatable
  33606. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33607. * @returns a new Mesh
  33608. */
  33609. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33610. var options = {
  33611. shape: shape,
  33612. holes: holes,
  33613. depth: depth,
  33614. updatable: updatable,
  33615. sideOrientation: sideOrientation
  33616. };
  33617. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33618. };
  33619. /**
  33620. * Creates an extruded shape mesh.
  33621. * 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
  33622. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33623. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33624. * @param name defines the name of the mesh to create
  33625. * @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
  33626. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33627. * @param scale is the value to scale the shape
  33628. * @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
  33629. * @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
  33630. * @param scene defines the hosting scene
  33631. * @param updatable defines if the mesh must be flagged as updatable
  33632. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33633. * @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)
  33634. * @returns a new Mesh
  33635. */
  33636. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33637. if (scene === void 0) { scene = null; }
  33638. var options = {
  33639. shape: shape,
  33640. path: path,
  33641. scale: scale,
  33642. rotation: rotation,
  33643. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33644. sideOrientation: sideOrientation,
  33645. instance: instance,
  33646. updatable: updatable
  33647. };
  33648. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33649. };
  33650. /**
  33651. * Creates an custom extruded shape mesh.
  33652. * The custom extrusion is a parametric shape.
  33653. * It has no predefined shape. Its final shape will depend on the input parameters.
  33654. * Please consider using the same method from the MeshBuilder class instead
  33655. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33656. * @param name defines the name of the mesh to create
  33657. * @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
  33658. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33659. * @param scaleFunction is a custom Javascript function called on each path point
  33660. * @param rotationFunction is a custom Javascript function called on each path point
  33661. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33662. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33663. * @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
  33664. * @param scene defines the hosting scene
  33665. * @param updatable defines if the mesh must be flagged as updatable
  33666. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33667. * @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)
  33668. * @returns a new Mesh
  33669. */
  33670. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33671. var options = {
  33672. shape: shape,
  33673. path: path,
  33674. scaleFunction: scaleFunction,
  33675. rotationFunction: rotationFunction,
  33676. ribbonCloseArray: ribbonCloseArray,
  33677. ribbonClosePath: ribbonClosePath,
  33678. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33679. sideOrientation: sideOrientation,
  33680. instance: instance,
  33681. updatable: updatable
  33682. };
  33683. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33684. };
  33685. /**
  33686. * Creates lathe mesh.
  33687. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33688. * Please consider using the same method from the MeshBuilder class instead
  33689. * @param name defines the name of the mesh to create
  33690. * @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
  33691. * @param radius is the radius value of the lathe
  33692. * @param tessellation is the side number of the lathe.
  33693. * @param scene defines the hosting scene
  33694. * @param updatable defines if the mesh must be flagged as updatable
  33695. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33696. * @returns a new Mesh
  33697. */
  33698. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33699. var options = {
  33700. shape: shape,
  33701. radius: radius,
  33702. tessellation: tessellation,
  33703. sideOrientation: sideOrientation,
  33704. updatable: updatable
  33705. };
  33706. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33707. };
  33708. /**
  33709. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33710. * @param name defines the name of the mesh to create
  33711. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33712. * @param scene defines the hosting scene
  33713. * @param updatable defines if the mesh must be flagged as updatable
  33714. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33715. * @returns a new Mesh
  33716. */
  33717. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33718. var options = {
  33719. size: size,
  33720. width: size,
  33721. height: size,
  33722. sideOrientation: sideOrientation,
  33723. updatable: updatable
  33724. };
  33725. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33726. };
  33727. /**
  33728. * Creates a ground mesh.
  33729. * Please consider using the same method from the MeshBuilder class instead
  33730. * @param name defines the name of the mesh to create
  33731. * @param width set the width of the ground
  33732. * @param height set the height of the ground
  33733. * @param subdivisions sets the number of subdivisions per side
  33734. * @param scene defines the hosting scene
  33735. * @param updatable defines if the mesh must be flagged as updatable
  33736. * @returns a new Mesh
  33737. */
  33738. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33739. var options = {
  33740. width: width,
  33741. height: height,
  33742. subdivisions: subdivisions,
  33743. updatable: updatable
  33744. };
  33745. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33746. };
  33747. /**
  33748. * Creates a tiled ground mesh.
  33749. * Please consider using the same method from the MeshBuilder class instead
  33750. * @param name defines the name of the mesh to create
  33751. * @param xmin set the ground minimum X coordinate
  33752. * @param zmin set the ground minimum Y coordinate
  33753. * @param xmax set the ground maximum X coordinate
  33754. * @param zmax set the ground maximum Z coordinate
  33755. * @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
  33756. * @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
  33757. * @param scene defines the hosting scene
  33758. * @param updatable defines if the mesh must be flagged as updatable
  33759. * @returns a new Mesh
  33760. */
  33761. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33762. var options = {
  33763. xmin: xmin,
  33764. zmin: zmin,
  33765. xmax: xmax,
  33766. zmax: zmax,
  33767. subdivisions: subdivisions,
  33768. precision: precision,
  33769. updatable: updatable
  33770. };
  33771. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33772. };
  33773. /**
  33774. * Creates a ground mesh from a height map.
  33775. * Please consider using the same method from the MeshBuilder class instead
  33776. * @see http://doc.babylonjs.com/babylon101/height_map
  33777. * @param name defines the name of the mesh to create
  33778. * @param url sets the URL of the height map image resource
  33779. * @param width set the ground width size
  33780. * @param height set the ground height size
  33781. * @param subdivisions sets the number of subdivision per side
  33782. * @param minHeight is the minimum altitude on the ground
  33783. * @param maxHeight is the maximum altitude on the ground
  33784. * @param scene defines the hosting scene
  33785. * @param updatable defines if the mesh must be flagged as updatable
  33786. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33787. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33788. * @returns a new Mesh
  33789. */
  33790. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33791. var options = {
  33792. width: width,
  33793. height: height,
  33794. subdivisions: subdivisions,
  33795. minHeight: minHeight,
  33796. maxHeight: maxHeight,
  33797. updatable: updatable,
  33798. onReady: onReady,
  33799. alphaFilter: alphaFilter
  33800. };
  33801. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33802. };
  33803. /**
  33804. * Creates a tube mesh.
  33805. * The tube is a parametric shape.
  33806. * It has no predefined shape. Its final shape will depend on the input parameters.
  33807. * Please consider using the same method from the MeshBuilder class instead
  33808. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33809. * @param name defines the name of the mesh to create
  33810. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33811. * @param radius sets the tube radius size
  33812. * @param tessellation is the number of sides on the tubular surface
  33813. * @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
  33814. * @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
  33815. * @param scene defines the hosting scene
  33816. * @param updatable defines if the mesh must be flagged as updatable
  33817. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33818. * @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)
  33819. * @returns a new Mesh
  33820. */
  33821. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33822. var options = {
  33823. path: path,
  33824. radius: radius,
  33825. tessellation: tessellation,
  33826. radiusFunction: radiusFunction,
  33827. arc: 1,
  33828. cap: cap,
  33829. updatable: updatable,
  33830. sideOrientation: sideOrientation,
  33831. instance: instance
  33832. };
  33833. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33834. };
  33835. /**
  33836. * Creates a polyhedron mesh.
  33837. * Please consider using the same method from the MeshBuilder class instead.
  33838. * * 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
  33839. * * The parameter `size` (positive float, default 1) sets the polygon size
  33840. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33841. * * 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`
  33842. * * 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
  33843. * * 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)`)
  33844. * * 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
  33845. * * 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
  33846. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33847. * * 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
  33848. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33849. * @param name defines the name of the mesh to create
  33850. * @param options defines the options used to create the mesh
  33851. * @param scene defines the hosting scene
  33852. * @returns a new Mesh
  33853. */
  33854. Mesh.CreatePolyhedron = function (name, options, scene) {
  33855. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33856. };
  33857. /**
  33858. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33859. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33860. * * 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`)
  33861. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33862. * * 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
  33863. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33864. * * 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
  33865. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33866. * @param name defines the name of the mesh
  33867. * @param options defines the options used to create the mesh
  33868. * @param scene defines the hosting scene
  33869. * @returns a new Mesh
  33870. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33871. */
  33872. Mesh.CreateIcoSphere = function (name, options, scene) {
  33873. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33874. };
  33875. /**
  33876. * Creates a decal mesh.
  33877. * Please consider using the same method from the MeshBuilder class instead.
  33878. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33879. * @param name defines the name of the mesh
  33880. * @param sourceMesh defines the mesh receiving the decal
  33881. * @param position sets the position of the decal in world coordinates
  33882. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33883. * @param size sets the decal scaling
  33884. * @param angle sets the angle to rotate the decal
  33885. * @returns a new Mesh
  33886. */
  33887. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33888. var options = {
  33889. position: position,
  33890. normal: normal,
  33891. size: size,
  33892. angle: angle
  33893. };
  33894. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33895. };
  33896. // Skeletons
  33897. /**
  33898. * Prepare internal position array for software CPU skinning
  33899. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33900. */
  33901. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33902. if (!this._sourcePositions) {
  33903. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33904. if (!source) {
  33905. return this._sourcePositions;
  33906. }
  33907. this._sourcePositions = new Float32Array(source);
  33908. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33909. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33910. }
  33911. }
  33912. return this._sourcePositions;
  33913. };
  33914. /**
  33915. * Prepare internal normal array for software CPU skinning
  33916. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33917. */
  33918. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33919. if (!this._sourceNormals) {
  33920. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33921. if (!source) {
  33922. return this._sourceNormals;
  33923. }
  33924. this._sourceNormals = new Float32Array(source);
  33925. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33926. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33927. }
  33928. }
  33929. return this._sourceNormals;
  33930. };
  33931. /**
  33932. * Updates the vertex buffer by applying transformation from the bones
  33933. * @param skeleton defines the skeleton to apply to current mesh
  33934. * @returns the current mesh
  33935. */
  33936. Mesh.prototype.applySkeleton = function (skeleton) {
  33937. if (!this.geometry) {
  33938. return this;
  33939. }
  33940. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33941. return this;
  33942. }
  33943. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33944. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33945. return this;
  33946. }
  33947. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33948. return this;
  33949. }
  33950. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33951. return this;
  33952. }
  33953. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33954. return this;
  33955. }
  33956. if (!this._sourcePositions) {
  33957. var submeshes = this.subMeshes.slice();
  33958. this.setPositionsForCPUSkinning();
  33959. this.subMeshes = submeshes;
  33960. }
  33961. if (!this._sourceNormals) {
  33962. this.setNormalsForCPUSkinning();
  33963. }
  33964. // positionsData checks for not being Float32Array will only pass at most once
  33965. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33966. if (!positionsData) {
  33967. return this;
  33968. }
  33969. if (!(positionsData instanceof Float32Array)) {
  33970. positionsData = new Float32Array(positionsData);
  33971. }
  33972. // normalsData checks for not being Float32Array will only pass at most once
  33973. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33974. if (!normalsData) {
  33975. return this;
  33976. }
  33977. if (!(normalsData instanceof Float32Array)) {
  33978. normalsData = new Float32Array(normalsData);
  33979. }
  33980. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33981. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33982. if (!matricesWeightsData || !matricesIndicesData) {
  33983. return this;
  33984. }
  33985. var needExtras = this.numBoneInfluencers > 4;
  33986. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33987. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33988. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33989. var tempVector3 = BABYLON.Vector3.Zero();
  33990. var finalMatrix = new BABYLON.Matrix();
  33991. var tempMatrix = new BABYLON.Matrix();
  33992. var matWeightIdx = 0;
  33993. var inf;
  33994. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33995. var weight;
  33996. for (inf = 0; inf < 4; inf++) {
  33997. weight = matricesWeightsData[matWeightIdx + inf];
  33998. if (weight > 0) {
  33999. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34000. finalMatrix.addToSelf(tempMatrix);
  34001. }
  34002. }
  34003. if (needExtras) {
  34004. for (inf = 0; inf < 4; inf++) {
  34005. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34006. if (weight > 0) {
  34007. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34008. finalMatrix.addToSelf(tempMatrix);
  34009. }
  34010. }
  34011. }
  34012. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34013. tempVector3.toArray(positionsData, index);
  34014. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34015. tempVector3.toArray(normalsData, index);
  34016. finalMatrix.reset();
  34017. }
  34018. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34019. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34020. return this;
  34021. };
  34022. // Tools
  34023. /**
  34024. * 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
  34025. * @param meshes defines the list of meshes to scan
  34026. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34027. */
  34028. Mesh.MinMax = function (meshes) {
  34029. var minVector = null;
  34030. var maxVector = null;
  34031. meshes.forEach(function (mesh, index, array) {
  34032. var boundingInfo = mesh.getBoundingInfo();
  34033. var boundingBox = boundingInfo.boundingBox;
  34034. if (!minVector || !maxVector) {
  34035. minVector = boundingBox.minimumWorld;
  34036. maxVector = boundingBox.maximumWorld;
  34037. }
  34038. else {
  34039. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34040. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34041. }
  34042. });
  34043. if (!minVector || !maxVector) {
  34044. return {
  34045. min: BABYLON.Vector3.Zero(),
  34046. max: BABYLON.Vector3.Zero()
  34047. };
  34048. }
  34049. return {
  34050. min: minVector,
  34051. max: maxVector
  34052. };
  34053. };
  34054. /**
  34055. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34056. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34057. * @returns a vector3
  34058. */
  34059. Mesh.Center = function (meshesOrMinMaxVector) {
  34060. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34061. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34062. };
  34063. /**
  34064. * Merge the array of meshes into a single mesh for performance reasons.
  34065. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34066. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34067. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34068. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34069. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34070. * @returns a new mesh
  34071. */
  34072. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34073. if (disposeSource === void 0) { disposeSource = true; }
  34074. var index;
  34075. if (!allow32BitsIndices) {
  34076. var totalVertices = 0;
  34077. // Counting vertices
  34078. for (index = 0; index < meshes.length; index++) {
  34079. if (meshes[index]) {
  34080. totalVertices += meshes[index].getTotalVertices();
  34081. if (totalVertices > 65536) {
  34082. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34083. return null;
  34084. }
  34085. }
  34086. }
  34087. }
  34088. // Merge
  34089. var vertexData = null;
  34090. var otherVertexData;
  34091. var indiceArray = new Array();
  34092. var source = null;
  34093. for (index = 0; index < meshes.length; index++) {
  34094. if (meshes[index]) {
  34095. var wm = meshes[index].computeWorldMatrix(true);
  34096. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34097. otherVertexData.transform(wm);
  34098. if (vertexData) {
  34099. vertexData.merge(otherVertexData, allow32BitsIndices);
  34100. }
  34101. else {
  34102. vertexData = otherVertexData;
  34103. source = meshes[index];
  34104. }
  34105. if (subdivideWithSubMeshes) {
  34106. indiceArray.push(meshes[index].getTotalIndices());
  34107. }
  34108. }
  34109. }
  34110. source = source;
  34111. if (!meshSubclass) {
  34112. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34113. }
  34114. vertexData.applyToMesh(meshSubclass);
  34115. // Setting properties
  34116. meshSubclass.material = source.material;
  34117. meshSubclass.checkCollisions = source.checkCollisions;
  34118. // Cleaning
  34119. if (disposeSource) {
  34120. for (index = 0; index < meshes.length; index++) {
  34121. if (meshes[index]) {
  34122. meshes[index].dispose();
  34123. }
  34124. }
  34125. }
  34126. // Subdivide
  34127. if (subdivideWithSubMeshes) {
  34128. //-- removal of global submesh
  34129. meshSubclass.releaseSubMeshes();
  34130. index = 0;
  34131. var offset = 0;
  34132. //-- apply subdivision according to index table
  34133. while (index < indiceArray.length) {
  34134. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34135. offset += indiceArray[index];
  34136. index++;
  34137. }
  34138. }
  34139. return meshSubclass;
  34140. };
  34141. // Consts
  34142. /**
  34143. * Mesh side orientation : usually the external or front surface
  34144. */
  34145. Mesh.FRONTSIDE = 0;
  34146. /**
  34147. * Mesh side orientation : usually the internal or back surface
  34148. */
  34149. Mesh.BACKSIDE = 1;
  34150. /**
  34151. * Mesh side orientation : both internal and external or front and back surfaces
  34152. */
  34153. Mesh.DOUBLESIDE = 2;
  34154. /**
  34155. * Mesh side orientation : by default, `FRONTSIDE`
  34156. */
  34157. Mesh.DEFAULTSIDE = 0;
  34158. /**
  34159. * Mesh cap setting : no cap
  34160. */
  34161. Mesh.NO_CAP = 0;
  34162. /**
  34163. * Mesh cap setting : one cap at the beginning of the mesh
  34164. */
  34165. Mesh.CAP_START = 1;
  34166. /**
  34167. * Mesh cap setting : one cap at the end of the mesh
  34168. */
  34169. Mesh.CAP_END = 2;
  34170. /**
  34171. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34172. */
  34173. Mesh.CAP_ALL = 3;
  34174. return Mesh;
  34175. }(BABYLON.AbstractMesh));
  34176. BABYLON.Mesh = Mesh;
  34177. })(BABYLON || (BABYLON = {}));
  34178. //# sourceMappingURL=babylon.mesh.js.map
  34179. var BABYLON;
  34180. (function (BABYLON) {
  34181. var BaseSubMesh = /** @class */ (function () {
  34182. function BaseSubMesh() {
  34183. }
  34184. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34185. get: function () {
  34186. return this._materialEffect;
  34187. },
  34188. enumerable: true,
  34189. configurable: true
  34190. });
  34191. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34192. if (defines === void 0) { defines = null; }
  34193. if (this._materialEffect === effect) {
  34194. if (!effect) {
  34195. this._materialDefines = null;
  34196. }
  34197. return;
  34198. }
  34199. this._materialDefines = defines;
  34200. this._materialEffect = effect;
  34201. };
  34202. return BaseSubMesh;
  34203. }());
  34204. BABYLON.BaseSubMesh = BaseSubMesh;
  34205. var SubMesh = /** @class */ (function (_super) {
  34206. __extends(SubMesh, _super);
  34207. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34208. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34209. var _this = _super.call(this) || this;
  34210. _this.materialIndex = materialIndex;
  34211. _this.verticesStart = verticesStart;
  34212. _this.verticesCount = verticesCount;
  34213. _this.indexStart = indexStart;
  34214. _this.indexCount = indexCount;
  34215. /** @hidden */
  34216. _this._renderId = 0;
  34217. _this._mesh = mesh;
  34218. _this._renderingMesh = renderingMesh || mesh;
  34219. mesh.subMeshes.push(_this);
  34220. _this._trianglePlanes = [];
  34221. _this._id = mesh.subMeshes.length - 1;
  34222. if (createBoundingBox) {
  34223. _this.refreshBoundingInfo();
  34224. mesh.computeWorldMatrix(true);
  34225. }
  34226. return _this;
  34227. }
  34228. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34229. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34230. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34231. };
  34232. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34233. get: function () {
  34234. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  34235. },
  34236. enumerable: true,
  34237. configurable: true
  34238. });
  34239. /**
  34240. * Returns the submesh BoudingInfo object.
  34241. */
  34242. SubMesh.prototype.getBoundingInfo = function () {
  34243. if (this.IsGlobal) {
  34244. return this._mesh.getBoundingInfo();
  34245. }
  34246. return this._boundingInfo;
  34247. };
  34248. /**
  34249. * Sets the submesh BoundingInfo.
  34250. * Return the SubMesh.
  34251. */
  34252. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34253. this._boundingInfo = boundingInfo;
  34254. return this;
  34255. };
  34256. /**
  34257. * Returns the mesh of the current submesh.
  34258. */
  34259. SubMesh.prototype.getMesh = function () {
  34260. return this._mesh;
  34261. };
  34262. /**
  34263. * Returns the rendering mesh of the submesh.
  34264. */
  34265. SubMesh.prototype.getRenderingMesh = function () {
  34266. return this._renderingMesh;
  34267. };
  34268. /**
  34269. * Returns the submesh material.
  34270. */
  34271. SubMesh.prototype.getMaterial = function () {
  34272. var rootMaterial = this._renderingMesh.material;
  34273. if (rootMaterial === null || rootMaterial === undefined) {
  34274. return this._mesh.getScene().defaultMaterial;
  34275. }
  34276. else if (rootMaterial.getSubMaterial) {
  34277. var multiMaterial = rootMaterial;
  34278. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34279. if (this._currentMaterial !== effectiveMaterial) {
  34280. this._currentMaterial = effectiveMaterial;
  34281. this._materialDefines = null;
  34282. }
  34283. return effectiveMaterial;
  34284. }
  34285. return rootMaterial;
  34286. };
  34287. // Methods
  34288. /**
  34289. * Sets a new updated BoundingInfo object to the submesh.
  34290. * Returns the SubMesh.
  34291. */
  34292. SubMesh.prototype.refreshBoundingInfo = function () {
  34293. this._lastColliderWorldVertices = null;
  34294. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34295. return this;
  34296. }
  34297. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34298. if (!data) {
  34299. this._boundingInfo = this._mesh.getBoundingInfo();
  34300. return this;
  34301. }
  34302. var indices = this._renderingMesh.getIndices();
  34303. var extend;
  34304. //is this the only submesh?
  34305. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34306. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34307. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34308. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34309. }
  34310. else {
  34311. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34312. }
  34313. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34314. return this;
  34315. };
  34316. /** @hidden */
  34317. SubMesh.prototype._checkCollision = function (collider) {
  34318. var boundingInfo = this.getBoundingInfo();
  34319. return boundingInfo._checkCollision(collider);
  34320. };
  34321. /**
  34322. * Updates the submesh BoundingInfo.
  34323. * Returns the Submesh.
  34324. */
  34325. SubMesh.prototype.updateBoundingInfo = function (world) {
  34326. var boundingInfo = this.getBoundingInfo();
  34327. if (!boundingInfo) {
  34328. this.refreshBoundingInfo();
  34329. boundingInfo = this.getBoundingInfo();
  34330. }
  34331. boundingInfo.update(world);
  34332. return this;
  34333. };
  34334. /**
  34335. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34336. * Boolean returned.
  34337. */
  34338. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34339. var boundingInfo = this.getBoundingInfo();
  34340. if (!boundingInfo) {
  34341. return false;
  34342. }
  34343. return boundingInfo.isInFrustum(frustumPlanes);
  34344. };
  34345. /**
  34346. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34347. * Boolean returned.
  34348. */
  34349. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34350. var boundingInfo = this.getBoundingInfo();
  34351. if (!boundingInfo) {
  34352. return false;
  34353. }
  34354. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34355. };
  34356. /**
  34357. * Renders the submesh.
  34358. * Returns it.
  34359. */
  34360. SubMesh.prototype.render = function (enableAlphaMode) {
  34361. this._renderingMesh.render(this, enableAlphaMode);
  34362. return this;
  34363. };
  34364. /**
  34365. * Returns a new Index Buffer.
  34366. * Type returned : WebGLBuffer.
  34367. */
  34368. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34369. if (!this._linesIndexBuffer) {
  34370. var linesIndices = [];
  34371. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34372. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34373. }
  34374. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34375. this.linesIndexCount = linesIndices.length;
  34376. }
  34377. return this._linesIndexBuffer;
  34378. };
  34379. /**
  34380. * True is the passed Ray intersects the submesh bounding box.
  34381. * Boolean returned.
  34382. */
  34383. SubMesh.prototype.canIntersects = function (ray) {
  34384. var boundingInfo = this.getBoundingInfo();
  34385. if (!boundingInfo) {
  34386. return false;
  34387. }
  34388. return ray.intersectsBox(boundingInfo.boundingBox);
  34389. };
  34390. /**
  34391. * Returns an object IntersectionInfo.
  34392. */
  34393. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34394. var intersectInfo = null;
  34395. var material = this.getMaterial();
  34396. if (!material) {
  34397. return null;
  34398. }
  34399. switch (material.fillMode) {
  34400. case BABYLON.Material.PointListDrawMode:
  34401. case BABYLON.Material.LineListDrawMode:
  34402. case BABYLON.Material.LineLoopDrawMode:
  34403. case BABYLON.Material.LineStripDrawMode:
  34404. case BABYLON.Material.TriangleFanDrawMode:
  34405. case BABYLON.Material.TriangleStripDrawMode:
  34406. return null;
  34407. }
  34408. // LineMesh first as it's also a Mesh...
  34409. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34410. var lineMesh = this._mesh;
  34411. // Line test
  34412. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34413. var p0 = positions[indices[index]];
  34414. var p1 = positions[indices[index + 1]];
  34415. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34416. if (length < 0) {
  34417. continue;
  34418. }
  34419. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34420. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34421. if (fastCheck) {
  34422. break;
  34423. }
  34424. }
  34425. }
  34426. }
  34427. else {
  34428. // Triangles test
  34429. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34430. var p0 = positions[indices[index]];
  34431. var p1 = positions[indices[index + 1]];
  34432. var p2 = positions[indices[index + 2]];
  34433. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34434. if (currentIntersectInfo) {
  34435. if (currentIntersectInfo.distance < 0) {
  34436. continue;
  34437. }
  34438. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34439. intersectInfo = currentIntersectInfo;
  34440. intersectInfo.faceId = index / 3;
  34441. if (fastCheck) {
  34442. break;
  34443. }
  34444. }
  34445. }
  34446. }
  34447. }
  34448. return intersectInfo;
  34449. };
  34450. /** @hidden */
  34451. SubMesh.prototype._rebuild = function () {
  34452. if (this._linesIndexBuffer) {
  34453. this._linesIndexBuffer = null;
  34454. }
  34455. };
  34456. // Clone
  34457. /**
  34458. * Creates a new Submesh from the passed Mesh.
  34459. */
  34460. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34461. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34462. if (!this.IsGlobal) {
  34463. var boundingInfo = this.getBoundingInfo();
  34464. if (!boundingInfo) {
  34465. return result;
  34466. }
  34467. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34468. }
  34469. return result;
  34470. };
  34471. // Dispose
  34472. /**
  34473. * Disposes the Submesh.
  34474. * Returns nothing.
  34475. */
  34476. SubMesh.prototype.dispose = function () {
  34477. if (this._linesIndexBuffer) {
  34478. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34479. this._linesIndexBuffer = null;
  34480. }
  34481. // Remove from mesh
  34482. var index = this._mesh.subMeshes.indexOf(this);
  34483. this._mesh.subMeshes.splice(index, 1);
  34484. };
  34485. // Statics
  34486. /**
  34487. * Creates a new Submesh from the passed parameters :
  34488. * - materialIndex (integer) : the index of the main mesh material.
  34489. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34490. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34491. * - mesh (Mesh) : the main mesh to create the submesh from.
  34492. * - renderingMesh (optional Mesh) : rendering mesh.
  34493. */
  34494. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34495. var minVertexIndex = Number.MAX_VALUE;
  34496. var maxVertexIndex = -Number.MAX_VALUE;
  34497. renderingMesh = (renderingMesh || mesh);
  34498. var indices = renderingMesh.getIndices();
  34499. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34500. var vertexIndex = indices[index];
  34501. if (vertexIndex < minVertexIndex)
  34502. minVertexIndex = vertexIndex;
  34503. if (vertexIndex > maxVertexIndex)
  34504. maxVertexIndex = vertexIndex;
  34505. }
  34506. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34507. };
  34508. return SubMesh;
  34509. }(BaseSubMesh));
  34510. BABYLON.SubMesh = SubMesh;
  34511. })(BABYLON || (BABYLON = {}));
  34512. //# sourceMappingURL=babylon.subMesh.js.map
  34513. var __assign = (this && this.__assign) || function () {
  34514. __assign = Object.assign || function(t) {
  34515. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34516. s = arguments[i];
  34517. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34518. t[p] = s[p];
  34519. }
  34520. return t;
  34521. };
  34522. return __assign.apply(this, arguments);
  34523. };
  34524. var BABYLON;
  34525. (function (BABYLON) {
  34526. /**
  34527. * Manages the defines for the Material
  34528. */
  34529. var MaterialDefines = /** @class */ (function () {
  34530. function MaterialDefines() {
  34531. this._isDirty = true;
  34532. /** @hidden */
  34533. this._areLightsDirty = true;
  34534. /** @hidden */
  34535. this._areAttributesDirty = true;
  34536. /** @hidden */
  34537. this._areTexturesDirty = true;
  34538. /** @hidden */
  34539. this._areFresnelDirty = true;
  34540. /** @hidden */
  34541. this._areMiscDirty = true;
  34542. /** @hidden */
  34543. this._areImageProcessingDirty = true;
  34544. /** @hidden */
  34545. this._normals = false;
  34546. /** @hidden */
  34547. this._uvs = false;
  34548. /** @hidden */
  34549. this._needNormals = false;
  34550. /** @hidden */
  34551. this._needUVs = false;
  34552. }
  34553. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34554. /**
  34555. * Specifies if the material needs to be re-calculated
  34556. */
  34557. get: function () {
  34558. return this._isDirty;
  34559. },
  34560. enumerable: true,
  34561. configurable: true
  34562. });
  34563. /**
  34564. * Marks the material to indicate that it has been re-calculated
  34565. */
  34566. MaterialDefines.prototype.markAsProcessed = function () {
  34567. this._isDirty = false;
  34568. this._areAttributesDirty = false;
  34569. this._areTexturesDirty = false;
  34570. this._areFresnelDirty = false;
  34571. this._areLightsDirty = false;
  34572. this._areMiscDirty = false;
  34573. this._areImageProcessingDirty = false;
  34574. };
  34575. /**
  34576. * Marks the material to indicate that it needs to be re-calculated
  34577. */
  34578. MaterialDefines.prototype.markAsUnprocessed = function () {
  34579. this._isDirty = true;
  34580. };
  34581. /**
  34582. * Marks the material to indicate all of its defines need to be re-calculated
  34583. */
  34584. MaterialDefines.prototype.markAllAsDirty = function () {
  34585. this._areTexturesDirty = true;
  34586. this._areAttributesDirty = true;
  34587. this._areLightsDirty = true;
  34588. this._areFresnelDirty = true;
  34589. this._areMiscDirty = true;
  34590. this._areImageProcessingDirty = true;
  34591. this._isDirty = true;
  34592. };
  34593. /**
  34594. * Marks the material to indicate that image processing needs to be re-calculated
  34595. */
  34596. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34597. this._areImageProcessingDirty = true;
  34598. this._isDirty = true;
  34599. };
  34600. /**
  34601. * Marks the material to indicate the lights need to be re-calculated
  34602. */
  34603. MaterialDefines.prototype.markAsLightDirty = function () {
  34604. this._areLightsDirty = true;
  34605. this._isDirty = true;
  34606. };
  34607. /**
  34608. * Marks the attribute state as changed
  34609. */
  34610. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34611. this._areAttributesDirty = true;
  34612. this._isDirty = true;
  34613. };
  34614. /**
  34615. * Marks the texture state as changed
  34616. */
  34617. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34618. this._areTexturesDirty = true;
  34619. this._isDirty = true;
  34620. };
  34621. /**
  34622. * Marks the fresnel state as changed
  34623. */
  34624. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34625. this._areFresnelDirty = true;
  34626. this._isDirty = true;
  34627. };
  34628. /**
  34629. * Marks the misc state as changed
  34630. */
  34631. MaterialDefines.prototype.markAsMiscDirty = function () {
  34632. this._areMiscDirty = true;
  34633. this._isDirty = true;
  34634. };
  34635. /**
  34636. * Rebuilds the material defines
  34637. */
  34638. MaterialDefines.prototype.rebuild = function () {
  34639. if (this._keys) {
  34640. delete this._keys;
  34641. }
  34642. this._keys = [];
  34643. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34644. var key = _a[_i];
  34645. if (key[0] === "_") {
  34646. continue;
  34647. }
  34648. this._keys.push(key);
  34649. }
  34650. };
  34651. /**
  34652. * Specifies if two material defines are equal
  34653. * @param other - A material define instance to compare to
  34654. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34655. */
  34656. MaterialDefines.prototype.isEqual = function (other) {
  34657. if (this._keys.length !== other._keys.length) {
  34658. return false;
  34659. }
  34660. for (var index = 0; index < this._keys.length; index++) {
  34661. var prop = this._keys[index];
  34662. if (this[prop] !== other[prop]) {
  34663. return false;
  34664. }
  34665. }
  34666. return true;
  34667. };
  34668. /**
  34669. * Clones this instance's defines to another instance
  34670. * @param other - material defines to clone values to
  34671. */
  34672. MaterialDefines.prototype.cloneTo = function (other) {
  34673. if (this._keys.length !== other._keys.length) {
  34674. other._keys = this._keys.slice(0);
  34675. }
  34676. for (var index = 0; index < this._keys.length; index++) {
  34677. var prop = this._keys[index];
  34678. other[prop] = this[prop];
  34679. }
  34680. };
  34681. /**
  34682. * Resets the material define values
  34683. */
  34684. MaterialDefines.prototype.reset = function () {
  34685. for (var index = 0; index < this._keys.length; index++) {
  34686. var prop = this._keys[index];
  34687. var type = typeof this[prop];
  34688. switch (type) {
  34689. case "number":
  34690. this[prop] = 0;
  34691. break;
  34692. case "string":
  34693. this[prop] = "";
  34694. break;
  34695. default:
  34696. this[prop] = false;
  34697. break;
  34698. }
  34699. }
  34700. };
  34701. /**
  34702. * Converts the material define values to a string
  34703. * @returns - String of material define information
  34704. */
  34705. MaterialDefines.prototype.toString = function () {
  34706. var result = "";
  34707. for (var index = 0; index < this._keys.length; index++) {
  34708. var prop = this._keys[index];
  34709. var value = this[prop];
  34710. var type = typeof value;
  34711. switch (type) {
  34712. case "number":
  34713. case "string":
  34714. result += "#define " + prop + " " + value + "\n";
  34715. break;
  34716. default:
  34717. if (value) {
  34718. result += "#define " + prop + "\n";
  34719. }
  34720. break;
  34721. }
  34722. }
  34723. return result;
  34724. };
  34725. return MaterialDefines;
  34726. }());
  34727. BABYLON.MaterialDefines = MaterialDefines;
  34728. /**
  34729. * Base class for the main features of a material in Babylon.js
  34730. */
  34731. var Material = /** @class */ (function () {
  34732. /**
  34733. * Creates a material instance
  34734. * @param name defines the name of the material
  34735. * @param scene defines the scene to reference
  34736. * @param doNotAdd specifies if the material should be added to the scene
  34737. */
  34738. function Material(name, scene, doNotAdd) {
  34739. /**
  34740. * Specifies if the ready state should be checked on each call
  34741. */
  34742. this.checkReadyOnEveryCall = false;
  34743. /**
  34744. * Specifies if the ready state should be checked once
  34745. */
  34746. this.checkReadyOnlyOnce = false;
  34747. /**
  34748. * The state of the material
  34749. */
  34750. this.state = "";
  34751. /**
  34752. * The alpha value of the material
  34753. */
  34754. this._alpha = 1.0;
  34755. /**
  34756. * Specifies if back face culling is enabled
  34757. */
  34758. this._backFaceCulling = true;
  34759. /**
  34760. * Specifies if the material should be serialized
  34761. */
  34762. this.doNotSerialize = false;
  34763. /**
  34764. * Specifies if the effect should be stored on sub meshes
  34765. */
  34766. this.storeEffectOnSubMeshes = false;
  34767. /**
  34768. * An event triggered when the material is disposed
  34769. */
  34770. this.onDisposeObservable = new BABYLON.Observable();
  34771. /**
  34772. * Stores the value of the alpha mode
  34773. */
  34774. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34775. /**
  34776. * Stores the state of the need depth pre-pass value
  34777. */
  34778. this._needDepthPrePass = false;
  34779. /**
  34780. * Specifies if depth writing should be disabled
  34781. */
  34782. this.disableDepthWrite = false;
  34783. /**
  34784. * Specifies if depth writing should be forced
  34785. */
  34786. this.forceDepthWrite = false;
  34787. /**
  34788. * Specifies if there should be a separate pass for culling
  34789. */
  34790. this.separateCullingPass = false;
  34791. /**
  34792. * Stores the state specifing if fog should be enabled
  34793. */
  34794. this._fogEnabled = true;
  34795. /**
  34796. * Stores the size of points
  34797. */
  34798. this.pointSize = 1.0;
  34799. /**
  34800. * Stores the z offset value
  34801. */
  34802. this.zOffset = 0;
  34803. /**
  34804. * @hidden
  34805. * Specifies if the material was previously ready
  34806. */
  34807. this._wasPreviouslyReady = false;
  34808. /**
  34809. * Stores the fill mode state
  34810. */
  34811. this._fillMode = Material.TriangleFillMode;
  34812. this.name = name;
  34813. this.id = name || BABYLON.Tools.RandomId();
  34814. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34815. this.uniqueId = this._scene.getUniqueId();
  34816. if (this._scene.useRightHandedSystem) {
  34817. this.sideOrientation = Material.ClockWiseSideOrientation;
  34818. }
  34819. else {
  34820. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34821. }
  34822. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34823. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34824. if (!doNotAdd) {
  34825. this._scene.materials.push(this);
  34826. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  34827. }
  34828. }
  34829. Object.defineProperty(Material, "TriangleFillMode", {
  34830. /**
  34831. * Returns the triangle fill mode
  34832. */
  34833. get: function () {
  34834. return Material._TriangleFillMode;
  34835. },
  34836. enumerable: true,
  34837. configurable: true
  34838. });
  34839. Object.defineProperty(Material, "WireFrameFillMode", {
  34840. /**
  34841. * Returns the wireframe mode
  34842. */
  34843. get: function () {
  34844. return Material._WireFrameFillMode;
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(Material, "PointFillMode", {
  34850. /**
  34851. * Returns the point fill mode
  34852. */
  34853. get: function () {
  34854. return Material._PointFillMode;
  34855. },
  34856. enumerable: true,
  34857. configurable: true
  34858. });
  34859. Object.defineProperty(Material, "PointListDrawMode", {
  34860. /**
  34861. * Returns the point list draw mode
  34862. */
  34863. get: function () {
  34864. return Material._PointListDrawMode;
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(Material, "LineListDrawMode", {
  34870. /**
  34871. * Returns the line list draw mode
  34872. */
  34873. get: function () {
  34874. return Material._LineListDrawMode;
  34875. },
  34876. enumerable: true,
  34877. configurable: true
  34878. });
  34879. Object.defineProperty(Material, "LineLoopDrawMode", {
  34880. /**
  34881. * Returns the line loop draw mode
  34882. */
  34883. get: function () {
  34884. return Material._LineLoopDrawMode;
  34885. },
  34886. enumerable: true,
  34887. configurable: true
  34888. });
  34889. Object.defineProperty(Material, "LineStripDrawMode", {
  34890. /**
  34891. * Returns the line strip draw mode
  34892. */
  34893. get: function () {
  34894. return Material._LineStripDrawMode;
  34895. },
  34896. enumerable: true,
  34897. configurable: true
  34898. });
  34899. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34900. /**
  34901. * Returns the triangle strip draw mode
  34902. */
  34903. get: function () {
  34904. return Material._TriangleStripDrawMode;
  34905. },
  34906. enumerable: true,
  34907. configurable: true
  34908. });
  34909. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34910. /**
  34911. * Returns the triangle fan draw mode
  34912. */
  34913. get: function () {
  34914. return Material._TriangleFanDrawMode;
  34915. },
  34916. enumerable: true,
  34917. configurable: true
  34918. });
  34919. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34920. /**
  34921. * Returns the clock-wise side orientation
  34922. */
  34923. get: function () {
  34924. return Material._ClockWiseSideOrientation;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34930. /**
  34931. * Returns the counter clock-wise side orientation
  34932. */
  34933. get: function () {
  34934. return Material._CounterClockWiseSideOrientation;
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(Material.prototype, "alpha", {
  34940. /**
  34941. * Gets the alpha value of the material
  34942. */
  34943. get: function () {
  34944. return this._alpha;
  34945. },
  34946. /**
  34947. * Sets the alpha value of the material
  34948. */
  34949. set: function (value) {
  34950. if (this._alpha === value) {
  34951. return;
  34952. }
  34953. this._alpha = value;
  34954. this.markAsDirty(Material.MiscDirtyFlag);
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34960. /**
  34961. * Gets the back-face culling state
  34962. */
  34963. get: function () {
  34964. return this._backFaceCulling;
  34965. },
  34966. /**
  34967. * Sets the back-face culling state
  34968. */
  34969. set: function (value) {
  34970. if (this._backFaceCulling === value) {
  34971. return;
  34972. }
  34973. this._backFaceCulling = value;
  34974. this.markAsDirty(Material.TextureDirtyFlag);
  34975. },
  34976. enumerable: true,
  34977. configurable: true
  34978. });
  34979. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  34980. /**
  34981. * Gets a boolean indicating that current material needs to register RTT
  34982. */
  34983. get: function () {
  34984. return false;
  34985. },
  34986. enumerable: true,
  34987. configurable: true
  34988. });
  34989. Object.defineProperty(Material.prototype, "onDispose", {
  34990. /**
  34991. * Called during a dispose event
  34992. */
  34993. set: function (callback) {
  34994. if (this._onDisposeObserver) {
  34995. this.onDisposeObservable.remove(this._onDisposeObserver);
  34996. }
  34997. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(Material.prototype, "onBindObservable", {
  35003. /**
  35004. * An event triggered when the material is bound
  35005. */
  35006. get: function () {
  35007. if (!this._onBindObservable) {
  35008. this._onBindObservable = new BABYLON.Observable();
  35009. }
  35010. return this._onBindObservable;
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(Material.prototype, "onBind", {
  35016. /**
  35017. * Called during a bind event
  35018. */
  35019. set: function (callback) {
  35020. if (this._onBindObserver) {
  35021. this.onBindObservable.remove(this._onBindObserver);
  35022. }
  35023. this._onBindObserver = this.onBindObservable.add(callback);
  35024. },
  35025. enumerable: true,
  35026. configurable: true
  35027. });
  35028. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35029. /**
  35030. * An event triggered when the material is unbound
  35031. */
  35032. get: function () {
  35033. if (!this._onUnBindObservable) {
  35034. this._onUnBindObservable = new BABYLON.Observable();
  35035. }
  35036. return this._onUnBindObservable;
  35037. },
  35038. enumerable: true,
  35039. configurable: true
  35040. });
  35041. Object.defineProperty(Material.prototype, "alphaMode", {
  35042. /**
  35043. * Gets the value of the alpha mode
  35044. */
  35045. get: function () {
  35046. return this._alphaMode;
  35047. },
  35048. /**
  35049. * Sets the value of the alpha mode.
  35050. *
  35051. * | Value | Type | Description |
  35052. * | --- | --- | --- |
  35053. * | 0 | ALPHA_DISABLE | |
  35054. * | 1 | ALPHA_ADD | |
  35055. * | 2 | ALPHA_COMBINE | |
  35056. * | 3 | ALPHA_SUBTRACT | |
  35057. * | 4 | ALPHA_MULTIPLY | |
  35058. * | 5 | ALPHA_MAXIMIZED | |
  35059. * | 6 | ALPHA_ONEONE | |
  35060. * | 7 | ALPHA_PREMULTIPLIED | |
  35061. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35062. * | 9 | ALPHA_INTERPOLATE | |
  35063. * | 10 | ALPHA_SCREENMODE | |
  35064. *
  35065. */
  35066. set: function (value) {
  35067. if (this._alphaMode === value) {
  35068. return;
  35069. }
  35070. this._alphaMode = value;
  35071. this.markAsDirty(Material.TextureDirtyFlag);
  35072. },
  35073. enumerable: true,
  35074. configurable: true
  35075. });
  35076. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35077. /**
  35078. * Gets the depth pre-pass value
  35079. */
  35080. get: function () {
  35081. return this._needDepthPrePass;
  35082. },
  35083. /**
  35084. * Sets the need depth pre-pass value
  35085. */
  35086. set: function (value) {
  35087. if (this._needDepthPrePass === value) {
  35088. return;
  35089. }
  35090. this._needDepthPrePass = value;
  35091. if (this._needDepthPrePass) {
  35092. this.checkReadyOnEveryCall = true;
  35093. }
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(Material.prototype, "fogEnabled", {
  35099. /**
  35100. * Gets the value of the fog enabled state
  35101. */
  35102. get: function () {
  35103. return this._fogEnabled;
  35104. },
  35105. /**
  35106. * Sets the state for enabling fog
  35107. */
  35108. set: function (value) {
  35109. if (this._fogEnabled === value) {
  35110. return;
  35111. }
  35112. this._fogEnabled = value;
  35113. this.markAsDirty(Material.MiscDirtyFlag);
  35114. },
  35115. enumerable: true,
  35116. configurable: true
  35117. });
  35118. Object.defineProperty(Material.prototype, "wireframe", {
  35119. /**
  35120. * Gets a value specifying if wireframe mode is enabled
  35121. */
  35122. get: function () {
  35123. switch (this._fillMode) {
  35124. case Material.WireFrameFillMode:
  35125. case Material.LineListDrawMode:
  35126. case Material.LineLoopDrawMode:
  35127. case Material.LineStripDrawMode:
  35128. return true;
  35129. }
  35130. return this._scene.forceWireframe;
  35131. },
  35132. /**
  35133. * Sets the state of wireframe mode
  35134. */
  35135. set: function (value) {
  35136. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35137. },
  35138. enumerable: true,
  35139. configurable: true
  35140. });
  35141. Object.defineProperty(Material.prototype, "pointsCloud", {
  35142. /**
  35143. * Gets the value specifying if point clouds are enabled
  35144. */
  35145. get: function () {
  35146. switch (this._fillMode) {
  35147. case Material.PointFillMode:
  35148. case Material.PointListDrawMode:
  35149. return true;
  35150. }
  35151. return this._scene.forcePointsCloud;
  35152. },
  35153. /**
  35154. * Sets the state of point cloud mode
  35155. */
  35156. set: function (value) {
  35157. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35158. },
  35159. enumerable: true,
  35160. configurable: true
  35161. });
  35162. Object.defineProperty(Material.prototype, "fillMode", {
  35163. /**
  35164. * Gets the material fill mode
  35165. */
  35166. get: function () {
  35167. return this._fillMode;
  35168. },
  35169. /**
  35170. * Sets the material fill mode
  35171. */
  35172. set: function (value) {
  35173. if (this._fillMode === value) {
  35174. return;
  35175. }
  35176. this._fillMode = value;
  35177. this.markAsDirty(Material.MiscDirtyFlag);
  35178. },
  35179. enumerable: true,
  35180. configurable: true
  35181. });
  35182. /**
  35183. * Returns a string representation of the current material
  35184. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35185. * @returns a string with material information
  35186. */
  35187. Material.prototype.toString = function (fullDetails) {
  35188. var ret = "Name: " + this.name;
  35189. if (fullDetails) {
  35190. }
  35191. return ret;
  35192. };
  35193. /**
  35194. * Gets the class name of the material
  35195. * @returns a string with the class name of the material
  35196. */
  35197. Material.prototype.getClassName = function () {
  35198. return "Material";
  35199. };
  35200. Object.defineProperty(Material.prototype, "isFrozen", {
  35201. /**
  35202. * Specifies if updates for the material been locked
  35203. */
  35204. get: function () {
  35205. return this.checkReadyOnlyOnce;
  35206. },
  35207. enumerable: true,
  35208. configurable: true
  35209. });
  35210. /**
  35211. * Locks updates for the material
  35212. */
  35213. Material.prototype.freeze = function () {
  35214. this.checkReadyOnlyOnce = true;
  35215. };
  35216. /**
  35217. * Unlocks updates for the material
  35218. */
  35219. Material.prototype.unfreeze = function () {
  35220. this.checkReadyOnlyOnce = false;
  35221. };
  35222. /**
  35223. * Specifies if the material is ready to be used
  35224. * @param mesh defines the mesh to check
  35225. * @param useInstances specifies if instances should be used
  35226. * @returns a boolean indicating if the material is ready to be used
  35227. */
  35228. Material.prototype.isReady = function (mesh, useInstances) {
  35229. return true;
  35230. };
  35231. /**
  35232. * Specifies that the submesh is ready to be used
  35233. * @param mesh defines the mesh to check
  35234. * @param subMesh defines which submesh to check
  35235. * @param useInstances specifies that instances should be used
  35236. * @returns a boolean indicating that the submesh is ready or not
  35237. */
  35238. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35239. return false;
  35240. };
  35241. /**
  35242. * Returns the material effect
  35243. * @returns the effect associated with the material
  35244. */
  35245. Material.prototype.getEffect = function () {
  35246. return this._effect;
  35247. };
  35248. /**
  35249. * Returns the current scene
  35250. * @returns a Scene
  35251. */
  35252. Material.prototype.getScene = function () {
  35253. return this._scene;
  35254. };
  35255. /**
  35256. * Specifies if the material will require alpha blending
  35257. * @returns a boolean specifying if alpha blending is needed
  35258. */
  35259. Material.prototype.needAlphaBlending = function () {
  35260. return (this.alpha < 1.0);
  35261. };
  35262. /**
  35263. * Specifies if the mesh will require alpha blending
  35264. * @param mesh defines the mesh to check
  35265. * @returns a boolean specifying if alpha blending is needed for the mesh
  35266. */
  35267. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35268. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35269. };
  35270. /**
  35271. * Specifies if this material should be rendered in alpha test mode
  35272. * @returns a boolean specifying if an alpha test is needed.
  35273. */
  35274. Material.prototype.needAlphaTesting = function () {
  35275. return false;
  35276. };
  35277. /**
  35278. * Gets the texture used for the alpha test
  35279. * @returns the texture to use for alpha testing
  35280. */
  35281. Material.prototype.getAlphaTestTexture = function () {
  35282. return null;
  35283. };
  35284. /**
  35285. * Marks the material to indicate that it needs to be re-calculated
  35286. */
  35287. Material.prototype.markDirty = function () {
  35288. this._wasPreviouslyReady = false;
  35289. };
  35290. /** @hidden */
  35291. Material.prototype._preBind = function (effect, overrideOrientation) {
  35292. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35293. var engine = this._scene.getEngine();
  35294. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35295. var reverse = orientation === Material.ClockWiseSideOrientation;
  35296. engine.enableEffect(effect ? effect : this._effect);
  35297. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35298. return reverse;
  35299. };
  35300. /**
  35301. * Binds the material to the mesh
  35302. * @param world defines the world transformation matrix
  35303. * @param mesh defines the mesh to bind the material to
  35304. */
  35305. Material.prototype.bind = function (world, mesh) {
  35306. };
  35307. /**
  35308. * Binds the submesh to the material
  35309. * @param world defines the world transformation matrix
  35310. * @param mesh defines the mesh containing the submesh
  35311. * @param subMesh defines the submesh to bind the material to
  35312. */
  35313. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35314. };
  35315. /**
  35316. * Binds the world matrix to the material
  35317. * @param world defines the world transformation matrix
  35318. */
  35319. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35320. };
  35321. /**
  35322. * Binds the scene's uniform buffer to the effect.
  35323. * @param effect defines the effect to bind to the scene uniform buffer
  35324. * @param sceneUbo defines the uniform buffer storing scene data
  35325. */
  35326. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35327. sceneUbo.bindToEffect(effect, "Scene");
  35328. };
  35329. /**
  35330. * Binds the view matrix to the effect
  35331. * @param effect defines the effect to bind the view matrix to
  35332. */
  35333. Material.prototype.bindView = function (effect) {
  35334. if (!this._useUBO) {
  35335. effect.setMatrix("view", this.getScene().getViewMatrix());
  35336. }
  35337. else {
  35338. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35339. }
  35340. };
  35341. /**
  35342. * Binds the view projection matrix to the effect
  35343. * @param effect defines the effect to bind the view projection matrix to
  35344. */
  35345. Material.prototype.bindViewProjection = function (effect) {
  35346. if (!this._useUBO) {
  35347. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35348. }
  35349. else {
  35350. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35351. }
  35352. };
  35353. /**
  35354. * Specifies if material alpha testing should be turned on for the mesh
  35355. * @param mesh defines the mesh to check
  35356. */
  35357. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35358. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35359. };
  35360. /**
  35361. * Processes to execute after binding the material to a mesh
  35362. * @param mesh defines the rendered mesh
  35363. */
  35364. Material.prototype._afterBind = function (mesh) {
  35365. this._scene._cachedMaterial = this;
  35366. if (mesh) {
  35367. this._scene._cachedVisibility = mesh.visibility;
  35368. }
  35369. else {
  35370. this._scene._cachedVisibility = 1;
  35371. }
  35372. if (this._onBindObservable && mesh) {
  35373. this._onBindObservable.notifyObservers(mesh);
  35374. }
  35375. if (this.disableDepthWrite) {
  35376. var engine = this._scene.getEngine();
  35377. this._cachedDepthWriteState = engine.getDepthWrite();
  35378. engine.setDepthWrite(false);
  35379. }
  35380. };
  35381. /**
  35382. * Unbinds the material from the mesh
  35383. */
  35384. Material.prototype.unbind = function () {
  35385. if (this._onUnBindObservable) {
  35386. this._onUnBindObservable.notifyObservers(this);
  35387. }
  35388. if (this.disableDepthWrite) {
  35389. var engine = this._scene.getEngine();
  35390. engine.setDepthWrite(this._cachedDepthWriteState);
  35391. }
  35392. };
  35393. /**
  35394. * Gets the active textures from the material
  35395. * @returns an array of textures
  35396. */
  35397. Material.prototype.getActiveTextures = function () {
  35398. return [];
  35399. };
  35400. /**
  35401. * Specifies if the material uses a texture
  35402. * @param texture defines the texture to check against the material
  35403. * @returns a boolean specifying if the material uses the texture
  35404. */
  35405. Material.prototype.hasTexture = function (texture) {
  35406. return false;
  35407. };
  35408. /**
  35409. * Makes a duplicate of the material, and gives it a new name
  35410. * @param name defines the new name for the duplicated material
  35411. * @returns the cloned material
  35412. */
  35413. Material.prototype.clone = function (name) {
  35414. return null;
  35415. };
  35416. /**
  35417. * Gets the meshes bound to the material
  35418. * @returns an array of meshes bound to the material
  35419. */
  35420. Material.prototype.getBindedMeshes = function () {
  35421. var result = new Array();
  35422. for (var index = 0; index < this._scene.meshes.length; index++) {
  35423. var mesh = this._scene.meshes[index];
  35424. if (mesh.material === this) {
  35425. result.push(mesh);
  35426. }
  35427. }
  35428. return result;
  35429. };
  35430. /**
  35431. * Force shader compilation
  35432. * @param mesh defines the mesh associated with this material
  35433. * @param onCompiled defines a function to execute once the material is compiled
  35434. * @param options defines the options to configure the compilation
  35435. */
  35436. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35437. var _this = this;
  35438. var localOptions = __assign({ clipPlane: false }, options);
  35439. var subMesh = new BABYLON.BaseSubMesh();
  35440. var scene = this.getScene();
  35441. var checkReady = function () {
  35442. if (!_this._scene || !_this._scene.getEngine()) {
  35443. return;
  35444. }
  35445. if (subMesh._materialDefines) {
  35446. subMesh._materialDefines._renderId = -1;
  35447. }
  35448. var clipPlaneState = scene.clipPlane;
  35449. if (localOptions.clipPlane) {
  35450. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35451. }
  35452. if (_this.storeEffectOnSubMeshes) {
  35453. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35454. if (onCompiled) {
  35455. onCompiled(_this);
  35456. }
  35457. }
  35458. else {
  35459. setTimeout(checkReady, 16);
  35460. }
  35461. }
  35462. else {
  35463. if (_this.isReady(mesh)) {
  35464. if (onCompiled) {
  35465. onCompiled(_this);
  35466. }
  35467. }
  35468. else {
  35469. setTimeout(checkReady, 16);
  35470. }
  35471. }
  35472. if (localOptions.clipPlane) {
  35473. scene.clipPlane = clipPlaneState;
  35474. }
  35475. };
  35476. checkReady();
  35477. };
  35478. /**
  35479. * Force shader compilation
  35480. * @param mesh defines the mesh that will use this material
  35481. * @param options defines additional options for compiling the shaders
  35482. * @returns a promise that resolves when the compilation completes
  35483. */
  35484. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35485. var _this = this;
  35486. return new Promise(function (resolve) {
  35487. _this.forceCompilation(mesh, function () {
  35488. resolve();
  35489. }, options);
  35490. });
  35491. };
  35492. /**
  35493. * Marks a define in the material to indicate that it needs to be re-computed
  35494. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35495. */
  35496. Material.prototype.markAsDirty = function (flag) {
  35497. if (flag & Material.TextureDirtyFlag) {
  35498. this._markAllSubMeshesAsTexturesDirty();
  35499. }
  35500. if (flag & Material.LightDirtyFlag) {
  35501. this._markAllSubMeshesAsLightsDirty();
  35502. }
  35503. if (flag & Material.FresnelDirtyFlag) {
  35504. this._markAllSubMeshesAsFresnelDirty();
  35505. }
  35506. if (flag & Material.AttributesDirtyFlag) {
  35507. this._markAllSubMeshesAsAttributesDirty();
  35508. }
  35509. if (flag & Material.MiscDirtyFlag) {
  35510. this._markAllSubMeshesAsMiscDirty();
  35511. }
  35512. this.getScene().resetCachedMaterial();
  35513. };
  35514. /**
  35515. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35516. * @param func defines a function which checks material defines against the submeshes
  35517. */
  35518. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35519. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35520. var mesh = _a[_i];
  35521. if (!mesh.subMeshes) {
  35522. continue;
  35523. }
  35524. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35525. var subMesh = _c[_b];
  35526. if (subMesh.getMaterial() !== this) {
  35527. continue;
  35528. }
  35529. if (!subMesh._materialDefines) {
  35530. continue;
  35531. }
  35532. func(subMesh._materialDefines);
  35533. }
  35534. }
  35535. };
  35536. /**
  35537. * Indicates that image processing needs to be re-calculated for all submeshes
  35538. */
  35539. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35540. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35541. };
  35542. /**
  35543. * Indicates that textures need to be re-calculated for all submeshes
  35544. */
  35545. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35546. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35547. };
  35548. /**
  35549. * Indicates that fresnel needs to be re-calculated for all submeshes
  35550. */
  35551. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35552. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35553. };
  35554. /**
  35555. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35556. */
  35557. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35558. this._markAllSubMeshesAsDirty(function (defines) {
  35559. defines.markAsFresnelDirty();
  35560. defines.markAsMiscDirty();
  35561. });
  35562. };
  35563. /**
  35564. * Indicates that lights need to be re-calculated for all submeshes
  35565. */
  35566. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35567. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35568. };
  35569. /**
  35570. * Indicates that attributes need to be re-calculated for all submeshes
  35571. */
  35572. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35573. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35574. };
  35575. /**
  35576. * Indicates that misc needs to be re-calculated for all submeshes
  35577. */
  35578. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35579. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35580. };
  35581. /**
  35582. * Indicates that textures and misc need to be re-calculated for all submeshes
  35583. */
  35584. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35585. this._markAllSubMeshesAsDirty(function (defines) {
  35586. defines.markAsTexturesDirty();
  35587. defines.markAsMiscDirty();
  35588. });
  35589. };
  35590. /**
  35591. * Disposes the material
  35592. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35593. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35594. */
  35595. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35596. // Animations
  35597. this.getScene().stopAnimation(this);
  35598. this.getScene().freeProcessedMaterials();
  35599. // Remove from scene
  35600. var index = this._scene.materials.indexOf(this);
  35601. if (index >= 0) {
  35602. this._scene.materials.splice(index, 1);
  35603. }
  35604. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  35605. // Remove from meshes
  35606. for (index = 0; index < this._scene.meshes.length; index++) {
  35607. var mesh = this._scene.meshes[index];
  35608. if (mesh.material === this) {
  35609. mesh.material = null;
  35610. if (mesh.geometry) {
  35611. var geometry = (mesh.geometry);
  35612. if (this.storeEffectOnSubMeshes) {
  35613. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35614. var subMesh = _a[_i];
  35615. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35616. if (forceDisposeEffect && subMesh._materialEffect) {
  35617. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35618. }
  35619. }
  35620. }
  35621. else {
  35622. geometry._releaseVertexArrayObject(this._effect);
  35623. }
  35624. }
  35625. }
  35626. }
  35627. this._uniformBuffer.dispose();
  35628. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35629. if (forceDisposeEffect && this._effect) {
  35630. if (!this.storeEffectOnSubMeshes) {
  35631. this._scene.getEngine()._releaseEffect(this._effect);
  35632. }
  35633. this._effect = null;
  35634. }
  35635. // Callback
  35636. this.onDisposeObservable.notifyObservers(this);
  35637. this.onDisposeObservable.clear();
  35638. if (this._onBindObservable) {
  35639. this._onBindObservable.clear();
  35640. }
  35641. if (this._onUnBindObservable) {
  35642. this._onUnBindObservable.clear();
  35643. }
  35644. };
  35645. /**
  35646. * Serializes this material
  35647. * @returns the serialized material object
  35648. */
  35649. Material.prototype.serialize = function () {
  35650. return BABYLON.SerializationHelper.Serialize(this);
  35651. };
  35652. /**
  35653. * Creates a MultiMaterial from parsed MultiMaterial data.
  35654. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35655. * @param scene defines the hosting scene
  35656. * @returns a new MultiMaterial
  35657. */
  35658. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35659. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35660. multiMaterial.id = parsedMultiMaterial.id;
  35661. if (BABYLON.Tags) {
  35662. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35663. }
  35664. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35665. var subMatId = parsedMultiMaterial.materials[matIndex];
  35666. if (subMatId) {
  35667. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35668. }
  35669. else {
  35670. multiMaterial.subMaterials.push(null);
  35671. }
  35672. }
  35673. return multiMaterial;
  35674. };
  35675. /**
  35676. * Creates a material from parsed material data
  35677. * @param parsedMaterial defines parsed material data
  35678. * @param scene defines the hosting scene
  35679. * @param rootUrl defines the root URL to use to load textures
  35680. * @returns a new material
  35681. */
  35682. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35683. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35684. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35685. }
  35686. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35687. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35688. if (!BABYLON.LegacyPBRMaterial) {
  35689. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35690. return;
  35691. }
  35692. }
  35693. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35694. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35695. };
  35696. // Triangle views
  35697. Material._TriangleFillMode = 0;
  35698. Material._WireFrameFillMode = 1;
  35699. Material._PointFillMode = 2;
  35700. // Draw modes
  35701. Material._PointListDrawMode = 3;
  35702. Material._LineListDrawMode = 4;
  35703. Material._LineLoopDrawMode = 5;
  35704. Material._LineStripDrawMode = 6;
  35705. Material._TriangleStripDrawMode = 7;
  35706. Material._TriangleFanDrawMode = 8;
  35707. /**
  35708. * Stores the clock-wise side orientation
  35709. */
  35710. Material._ClockWiseSideOrientation = 0;
  35711. /**
  35712. * Stores the counter clock-wise side orientation
  35713. */
  35714. Material._CounterClockWiseSideOrientation = 1;
  35715. /**
  35716. * The dirty texture flag value
  35717. */
  35718. Material.TextureDirtyFlag = 1;
  35719. /**
  35720. * The dirty light flag value
  35721. */
  35722. Material.LightDirtyFlag = 2;
  35723. /**
  35724. * The dirty fresnel flag value
  35725. */
  35726. Material.FresnelDirtyFlag = 4;
  35727. /**
  35728. * The dirty attribute flag value
  35729. */
  35730. Material.AttributesDirtyFlag = 8;
  35731. /**
  35732. * The dirty misc flag value
  35733. */
  35734. Material.MiscDirtyFlag = 16;
  35735. /**
  35736. * The all dirty flag value
  35737. */
  35738. Material.AllDirtyFlag = 31;
  35739. __decorate([
  35740. BABYLON.serialize()
  35741. ], Material.prototype, "id", void 0);
  35742. __decorate([
  35743. BABYLON.serialize()
  35744. ], Material.prototype, "uniqueId", void 0);
  35745. __decorate([
  35746. BABYLON.serialize()
  35747. ], Material.prototype, "name", void 0);
  35748. __decorate([
  35749. BABYLON.serialize()
  35750. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35751. __decorate([
  35752. BABYLON.serialize()
  35753. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35754. __decorate([
  35755. BABYLON.serialize()
  35756. ], Material.prototype, "state", void 0);
  35757. __decorate([
  35758. BABYLON.serialize("alpha")
  35759. ], Material.prototype, "_alpha", void 0);
  35760. __decorate([
  35761. BABYLON.serialize("backFaceCulling")
  35762. ], Material.prototype, "_backFaceCulling", void 0);
  35763. __decorate([
  35764. BABYLON.serialize()
  35765. ], Material.prototype, "sideOrientation", void 0);
  35766. __decorate([
  35767. BABYLON.serialize("alphaMode")
  35768. ], Material.prototype, "_alphaMode", void 0);
  35769. __decorate([
  35770. BABYLON.serialize()
  35771. ], Material.prototype, "_needDepthPrePass", void 0);
  35772. __decorate([
  35773. BABYLON.serialize()
  35774. ], Material.prototype, "disableDepthWrite", void 0);
  35775. __decorate([
  35776. BABYLON.serialize()
  35777. ], Material.prototype, "forceDepthWrite", void 0);
  35778. __decorate([
  35779. BABYLON.serialize()
  35780. ], Material.prototype, "separateCullingPass", void 0);
  35781. __decorate([
  35782. BABYLON.serialize("fogEnabled")
  35783. ], Material.prototype, "_fogEnabled", void 0);
  35784. __decorate([
  35785. BABYLON.serialize()
  35786. ], Material.prototype, "pointSize", void 0);
  35787. __decorate([
  35788. BABYLON.serialize()
  35789. ], Material.prototype, "zOffset", void 0);
  35790. __decorate([
  35791. BABYLON.serialize()
  35792. ], Material.prototype, "wireframe", null);
  35793. __decorate([
  35794. BABYLON.serialize()
  35795. ], Material.prototype, "pointsCloud", null);
  35796. __decorate([
  35797. BABYLON.serialize()
  35798. ], Material.prototype, "fillMode", null);
  35799. return Material;
  35800. }());
  35801. BABYLON.Material = Material;
  35802. })(BABYLON || (BABYLON = {}));
  35803. //# sourceMappingURL=babylon.material.js.map
  35804. var BABYLON;
  35805. (function (BABYLON) {
  35806. var UniformBuffer = /** @class */ (function () {
  35807. /**
  35808. * Uniform buffer objects.
  35809. *
  35810. * Handles blocks of uniform on the GPU.
  35811. *
  35812. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35813. *
  35814. * For more information, please refer to :
  35815. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35816. */
  35817. function UniformBuffer(engine, data, dynamic) {
  35818. this._engine = engine;
  35819. this._noUBO = !engine.supportsUniformBuffers;
  35820. this._dynamic = dynamic;
  35821. this._data = data || [];
  35822. this._uniformLocations = {};
  35823. this._uniformSizes = {};
  35824. this._uniformLocationPointer = 0;
  35825. this._needSync = false;
  35826. if (this._noUBO) {
  35827. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35828. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35829. this.updateFloat = this._updateFloatForEffect;
  35830. this.updateFloat2 = this._updateFloat2ForEffect;
  35831. this.updateFloat3 = this._updateFloat3ForEffect;
  35832. this.updateFloat4 = this._updateFloat4ForEffect;
  35833. this.updateMatrix = this._updateMatrixForEffect;
  35834. this.updateVector3 = this._updateVector3ForEffect;
  35835. this.updateVector4 = this._updateVector4ForEffect;
  35836. this.updateColor3 = this._updateColor3ForEffect;
  35837. this.updateColor4 = this._updateColor4ForEffect;
  35838. }
  35839. else {
  35840. this._engine._uniformBuffers.push(this);
  35841. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35842. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35843. this.updateFloat = this._updateFloatForUniform;
  35844. this.updateFloat2 = this._updateFloat2ForUniform;
  35845. this.updateFloat3 = this._updateFloat3ForUniform;
  35846. this.updateFloat4 = this._updateFloat4ForUniform;
  35847. this.updateMatrix = this._updateMatrixForUniform;
  35848. this.updateVector3 = this._updateVector3ForUniform;
  35849. this.updateVector4 = this._updateVector4ForUniform;
  35850. this.updateColor3 = this._updateColor3ForUniform;
  35851. this.updateColor4 = this._updateColor4ForUniform;
  35852. }
  35853. }
  35854. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35855. // Properties
  35856. /**
  35857. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35858. * or just falling back on setUniformXXX calls.
  35859. */
  35860. get: function () {
  35861. return !this._noUBO;
  35862. },
  35863. enumerable: true,
  35864. configurable: true
  35865. });
  35866. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35867. /**
  35868. * Indicates if the WebGL underlying uniform buffer is in sync
  35869. * with the javascript cache data.
  35870. */
  35871. get: function () {
  35872. return !this._needSync;
  35873. },
  35874. enumerable: true,
  35875. configurable: true
  35876. });
  35877. /**
  35878. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35879. * Also, a dynamic UniformBuffer will disable cache verification and always
  35880. * update the underlying WebGL uniform buffer to the GPU.
  35881. */
  35882. UniformBuffer.prototype.isDynamic = function () {
  35883. return this._dynamic !== undefined;
  35884. };
  35885. /**
  35886. * The data cache on JS side.
  35887. */
  35888. UniformBuffer.prototype.getData = function () {
  35889. return this._bufferData;
  35890. };
  35891. /**
  35892. * The underlying WebGL Uniform buffer.
  35893. */
  35894. UniformBuffer.prototype.getBuffer = function () {
  35895. return this._buffer;
  35896. };
  35897. /**
  35898. * std140 layout specifies how to align data within an UBO structure.
  35899. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35900. * for specs.
  35901. */
  35902. UniformBuffer.prototype._fillAlignment = function (size) {
  35903. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35904. // and 4x4 matrices
  35905. // TODO : change if other types are used
  35906. var alignment;
  35907. if (size <= 2) {
  35908. alignment = size;
  35909. }
  35910. else {
  35911. alignment = 4;
  35912. }
  35913. if ((this._uniformLocationPointer % alignment) !== 0) {
  35914. var oldPointer = this._uniformLocationPointer;
  35915. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35916. var diff = this._uniformLocationPointer - oldPointer;
  35917. for (var i = 0; i < diff; i++) {
  35918. this._data.push(0);
  35919. }
  35920. }
  35921. };
  35922. /**
  35923. * Adds an uniform in the buffer.
  35924. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35925. * for the layout to be correct !
  35926. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35927. * @param {number|number[]} size Data size, or data directly.
  35928. */
  35929. UniformBuffer.prototype.addUniform = function (name, size) {
  35930. if (this._noUBO) {
  35931. return;
  35932. }
  35933. if (this._uniformLocations[name] !== undefined) {
  35934. // Already existing uniform
  35935. return;
  35936. }
  35937. // This function must be called in the order of the shader layout !
  35938. // size can be the size of the uniform, or data directly
  35939. var data;
  35940. if (size instanceof Array) {
  35941. data = size;
  35942. size = data.length;
  35943. }
  35944. else {
  35945. size = size;
  35946. data = [];
  35947. // Fill with zeros
  35948. for (var i = 0; i < size; i++) {
  35949. data.push(0);
  35950. }
  35951. }
  35952. this._fillAlignment(size);
  35953. this._uniformSizes[name] = size;
  35954. this._uniformLocations[name] = this._uniformLocationPointer;
  35955. this._uniformLocationPointer += size;
  35956. for (var i = 0; i < size; i++) {
  35957. this._data.push(data[i]);
  35958. }
  35959. this._needSync = true;
  35960. };
  35961. /**
  35962. * Wrapper for addUniform.
  35963. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35964. * @param {Matrix} mat A 4x4 matrix.
  35965. */
  35966. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35967. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35968. };
  35969. /**
  35970. * Wrapper for addUniform.
  35971. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35972. * @param {number} x
  35973. * @param {number} y
  35974. */
  35975. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35976. var temp = [x, y];
  35977. this.addUniform(name, temp);
  35978. };
  35979. /**
  35980. * Wrapper for addUniform.
  35981. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35982. * @param {number} x
  35983. * @param {number} y
  35984. * @param {number} z
  35985. */
  35986. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35987. var temp = [x, y, z];
  35988. this.addUniform(name, temp);
  35989. };
  35990. /**
  35991. * Wrapper for addUniform.
  35992. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35993. * @param {Color3} color
  35994. */
  35995. UniformBuffer.prototype.addColor3 = function (name, color) {
  35996. var temp = new Array();
  35997. color.toArray(temp);
  35998. this.addUniform(name, temp);
  35999. };
  36000. /**
  36001. * Wrapper for addUniform.
  36002. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36003. * @param {Color3} color
  36004. * @param {number} alpha
  36005. */
  36006. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36007. var temp = new Array();
  36008. color.toArray(temp);
  36009. temp.push(alpha);
  36010. this.addUniform(name, temp);
  36011. };
  36012. /**
  36013. * Wrapper for addUniform.
  36014. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36015. * @param {Vector3} vector
  36016. */
  36017. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36018. var temp = new Array();
  36019. vector.toArray(temp);
  36020. this.addUniform(name, temp);
  36021. };
  36022. /**
  36023. * Wrapper for addUniform.
  36024. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36025. */
  36026. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36027. this.addUniform(name, 12);
  36028. };
  36029. /**
  36030. * Wrapper for addUniform.
  36031. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36032. */
  36033. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36034. this.addUniform(name, 8);
  36035. };
  36036. /**
  36037. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36038. */
  36039. UniformBuffer.prototype.create = function () {
  36040. if (this._noUBO) {
  36041. return;
  36042. }
  36043. if (this._buffer) {
  36044. return; // nothing to do
  36045. }
  36046. // See spec, alignment must be filled as a vec4
  36047. this._fillAlignment(4);
  36048. this._bufferData = new Float32Array(this._data);
  36049. this._rebuild();
  36050. this._needSync = true;
  36051. };
  36052. /** @hidden */
  36053. UniformBuffer.prototype._rebuild = function () {
  36054. if (this._noUBO) {
  36055. return;
  36056. }
  36057. if (this._dynamic) {
  36058. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36059. }
  36060. else {
  36061. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36062. }
  36063. };
  36064. /**
  36065. * Updates the WebGL Uniform Buffer on the GPU.
  36066. * If the `dynamic` flag is set to true, no cache comparison is done.
  36067. * Otherwise, the buffer will be updated only if the cache differs.
  36068. */
  36069. UniformBuffer.prototype.update = function () {
  36070. if (!this._buffer) {
  36071. this.create();
  36072. return;
  36073. }
  36074. if (!this._dynamic && !this._needSync) {
  36075. return;
  36076. }
  36077. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36078. this._needSync = false;
  36079. };
  36080. /**
  36081. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36082. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36083. * @param {number[]|Float32Array} data Flattened data
  36084. * @param {number} size Size of the data.
  36085. */
  36086. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36087. var location = this._uniformLocations[uniformName];
  36088. if (location === undefined) {
  36089. if (this._buffer) {
  36090. // Cannot add an uniform if the buffer is already created
  36091. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36092. return;
  36093. }
  36094. this.addUniform(uniformName, size);
  36095. location = this._uniformLocations[uniformName];
  36096. }
  36097. if (!this._buffer) {
  36098. this.create();
  36099. }
  36100. if (!this._dynamic) {
  36101. // Cache for static uniform buffers
  36102. var changed = false;
  36103. for (var i = 0; i < size; i++) {
  36104. if (this._bufferData[location + i] !== data[i]) {
  36105. changed = true;
  36106. this._bufferData[location + i] = data[i];
  36107. }
  36108. }
  36109. this._needSync = this._needSync || changed;
  36110. }
  36111. else {
  36112. // No cache for dynamic
  36113. for (var i = 0; i < size; i++) {
  36114. this._bufferData[location + i] = data[i];
  36115. }
  36116. }
  36117. };
  36118. // Update methods
  36119. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36120. // To match std140, matrix must be realigned
  36121. for (var i = 0; i < 3; i++) {
  36122. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36123. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36124. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36125. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36126. }
  36127. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36128. };
  36129. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36130. this._currentEffect.setMatrix3x3(name, matrix);
  36131. };
  36132. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36133. this._currentEffect.setMatrix2x2(name, matrix);
  36134. };
  36135. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36136. // To match std140, matrix must be realigned
  36137. for (var i = 0; i < 2; i++) {
  36138. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36139. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36140. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36141. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36142. }
  36143. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36144. };
  36145. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36146. this._currentEffect.setFloat(name, x);
  36147. };
  36148. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36149. UniformBuffer._tempBuffer[0] = x;
  36150. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36151. };
  36152. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36153. if (suffix === void 0) { suffix = ""; }
  36154. this._currentEffect.setFloat2(name + suffix, x, y);
  36155. };
  36156. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36157. if (suffix === void 0) { suffix = ""; }
  36158. UniformBuffer._tempBuffer[0] = x;
  36159. UniformBuffer._tempBuffer[1] = y;
  36160. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36161. };
  36162. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36163. if (suffix === void 0) { suffix = ""; }
  36164. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36165. };
  36166. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36167. if (suffix === void 0) { suffix = ""; }
  36168. UniformBuffer._tempBuffer[0] = x;
  36169. UniformBuffer._tempBuffer[1] = y;
  36170. UniformBuffer._tempBuffer[2] = z;
  36171. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36172. };
  36173. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36174. if (suffix === void 0) { suffix = ""; }
  36175. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36176. };
  36177. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36178. if (suffix === void 0) { suffix = ""; }
  36179. UniformBuffer._tempBuffer[0] = x;
  36180. UniformBuffer._tempBuffer[1] = y;
  36181. UniformBuffer._tempBuffer[2] = z;
  36182. UniformBuffer._tempBuffer[3] = w;
  36183. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36184. };
  36185. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36186. this._currentEffect.setMatrix(name, mat);
  36187. };
  36188. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36189. this.updateUniform(name, mat.toArray(), 16);
  36190. };
  36191. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36192. this._currentEffect.setVector3(name, vector);
  36193. };
  36194. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36195. vector.toArray(UniformBuffer._tempBuffer);
  36196. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36197. };
  36198. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36199. this._currentEffect.setVector4(name, vector);
  36200. };
  36201. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36202. vector.toArray(UniformBuffer._tempBuffer);
  36203. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36204. };
  36205. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36206. if (suffix === void 0) { suffix = ""; }
  36207. this._currentEffect.setColor3(name + suffix, color);
  36208. };
  36209. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36210. if (suffix === void 0) { suffix = ""; }
  36211. color.toArray(UniformBuffer._tempBuffer);
  36212. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36213. };
  36214. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36215. if (suffix === void 0) { suffix = ""; }
  36216. this._currentEffect.setColor4(name + suffix, color, alpha);
  36217. };
  36218. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36219. if (suffix === void 0) { suffix = ""; }
  36220. color.toArray(UniformBuffer._tempBuffer);
  36221. UniformBuffer._tempBuffer[3] = alpha;
  36222. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36223. };
  36224. /**
  36225. * Sets a sampler uniform on the effect.
  36226. * @param {string} name Name of the sampler.
  36227. * @param {Texture} texture
  36228. */
  36229. UniformBuffer.prototype.setTexture = function (name, texture) {
  36230. this._currentEffect.setTexture(name, texture);
  36231. };
  36232. /**
  36233. * Directly updates the value of the uniform in the cache AND on the GPU.
  36234. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36235. * @param {number[]|Float32Array} data Flattened data
  36236. */
  36237. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36238. this.updateUniform(uniformName, data, data.length);
  36239. this.update();
  36240. };
  36241. /**
  36242. * Binds this uniform buffer to an effect.
  36243. * @param {Effect} effect
  36244. * @param {string} name Name of the uniform block in the shader.
  36245. */
  36246. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36247. this._currentEffect = effect;
  36248. if (this._noUBO || !this._buffer) {
  36249. return;
  36250. }
  36251. effect.bindUniformBuffer(this._buffer, name);
  36252. };
  36253. /**
  36254. * Disposes the uniform buffer.
  36255. */
  36256. UniformBuffer.prototype.dispose = function () {
  36257. if (this._noUBO) {
  36258. return;
  36259. }
  36260. var index = this._engine._uniformBuffers.indexOf(this);
  36261. if (index !== -1) {
  36262. this._engine._uniformBuffers.splice(index, 1);
  36263. }
  36264. if (!this._buffer) {
  36265. return;
  36266. }
  36267. if (this._engine._releaseBuffer(this._buffer)) {
  36268. this._buffer = null;
  36269. }
  36270. };
  36271. // Pool for avoiding memory leaks
  36272. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36273. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36274. return UniformBuffer;
  36275. }());
  36276. BABYLON.UniformBuffer = UniformBuffer;
  36277. })(BABYLON || (BABYLON = {}));
  36278. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36279. var BABYLON;
  36280. (function (BABYLON) {
  36281. /**
  36282. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36283. */
  36284. var VertexData = /** @class */ (function () {
  36285. function VertexData() {
  36286. }
  36287. /**
  36288. * Uses the passed data array to set the set the values for the specified kind of data
  36289. * @param data a linear array of floating numbers
  36290. * @param kind the type of data that is being set, eg positions, colors etc
  36291. */
  36292. VertexData.prototype.set = function (data, kind) {
  36293. switch (kind) {
  36294. case BABYLON.VertexBuffer.PositionKind:
  36295. this.positions = data;
  36296. break;
  36297. case BABYLON.VertexBuffer.NormalKind:
  36298. this.normals = data;
  36299. break;
  36300. case BABYLON.VertexBuffer.TangentKind:
  36301. this.tangents = data;
  36302. break;
  36303. case BABYLON.VertexBuffer.UVKind:
  36304. this.uvs = data;
  36305. break;
  36306. case BABYLON.VertexBuffer.UV2Kind:
  36307. this.uvs2 = data;
  36308. break;
  36309. case BABYLON.VertexBuffer.UV3Kind:
  36310. this.uvs3 = data;
  36311. break;
  36312. case BABYLON.VertexBuffer.UV4Kind:
  36313. this.uvs4 = data;
  36314. break;
  36315. case BABYLON.VertexBuffer.UV5Kind:
  36316. this.uvs5 = data;
  36317. break;
  36318. case BABYLON.VertexBuffer.UV6Kind:
  36319. this.uvs6 = data;
  36320. break;
  36321. case BABYLON.VertexBuffer.ColorKind:
  36322. this.colors = data;
  36323. break;
  36324. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36325. this.matricesIndices = data;
  36326. break;
  36327. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36328. this.matricesWeights = data;
  36329. break;
  36330. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36331. this.matricesIndicesExtra = data;
  36332. break;
  36333. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36334. this.matricesWeightsExtra = data;
  36335. break;
  36336. }
  36337. };
  36338. /**
  36339. * Associates the vertexData to the passed Mesh.
  36340. * Sets it as updatable or not (default `false`)
  36341. * @param mesh the mesh the vertexData is applied to
  36342. * @param updatable when used and having the value true allows new data to update the vertexData
  36343. * @returns the VertexData
  36344. */
  36345. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36346. this._applyTo(mesh, updatable);
  36347. return this;
  36348. };
  36349. /**
  36350. * Associates the vertexData to the passed Geometry.
  36351. * Sets it as updatable or not (default `false`)
  36352. * @param geometry the geometry the vertexData is applied to
  36353. * @param updatable when used and having the value true allows new data to update the vertexData
  36354. * @returns VertexData
  36355. */
  36356. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36357. this._applyTo(geometry, updatable);
  36358. return this;
  36359. };
  36360. /**
  36361. * Updates the associated mesh
  36362. * @param mesh the mesh to be updated
  36363. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36364. * @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
  36365. * @returns VertexData
  36366. */
  36367. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36368. this._update(mesh);
  36369. return this;
  36370. };
  36371. /**
  36372. * Updates the associated geometry
  36373. * @param geometry the geometry to be updated
  36374. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36375. * @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
  36376. * @returns VertexData.
  36377. */
  36378. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36379. this._update(geometry);
  36380. return this;
  36381. };
  36382. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36383. if (updatable === void 0) { updatable = false; }
  36384. if (this.positions) {
  36385. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36386. }
  36387. if (this.normals) {
  36388. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36389. }
  36390. if (this.tangents) {
  36391. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36392. }
  36393. if (this.uvs) {
  36394. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36395. }
  36396. if (this.uvs2) {
  36397. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36398. }
  36399. if (this.uvs3) {
  36400. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36401. }
  36402. if (this.uvs4) {
  36403. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36404. }
  36405. if (this.uvs5) {
  36406. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36407. }
  36408. if (this.uvs6) {
  36409. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36410. }
  36411. if (this.colors) {
  36412. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36413. }
  36414. if (this.matricesIndices) {
  36415. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36416. }
  36417. if (this.matricesWeights) {
  36418. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36419. }
  36420. if (this.matricesIndicesExtra) {
  36421. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36422. }
  36423. if (this.matricesWeightsExtra) {
  36424. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36425. }
  36426. if (this.indices) {
  36427. meshOrGeometry.setIndices(this.indices, null, updatable);
  36428. }
  36429. else {
  36430. meshOrGeometry.setIndices([], null);
  36431. }
  36432. return this;
  36433. };
  36434. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36435. if (this.positions) {
  36436. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36437. }
  36438. if (this.normals) {
  36439. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36440. }
  36441. if (this.tangents) {
  36442. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36443. }
  36444. if (this.uvs) {
  36445. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36446. }
  36447. if (this.uvs2) {
  36448. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36449. }
  36450. if (this.uvs3) {
  36451. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36452. }
  36453. if (this.uvs4) {
  36454. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36455. }
  36456. if (this.uvs5) {
  36457. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36458. }
  36459. if (this.uvs6) {
  36460. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36461. }
  36462. if (this.colors) {
  36463. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36464. }
  36465. if (this.matricesIndices) {
  36466. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36467. }
  36468. if (this.matricesWeights) {
  36469. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36470. }
  36471. if (this.matricesIndicesExtra) {
  36472. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36473. }
  36474. if (this.matricesWeightsExtra) {
  36475. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36476. }
  36477. if (this.indices) {
  36478. meshOrGeometry.setIndices(this.indices, null);
  36479. }
  36480. return this;
  36481. };
  36482. /**
  36483. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36484. * @param matrix the transforming matrix
  36485. * @returns the VertexData
  36486. */
  36487. VertexData.prototype.transform = function (matrix) {
  36488. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36489. var transformed = BABYLON.Vector3.Zero();
  36490. var index;
  36491. if (this.positions) {
  36492. var position = BABYLON.Vector3.Zero();
  36493. for (index = 0; index < this.positions.length; index += 3) {
  36494. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36495. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36496. this.positions[index] = transformed.x;
  36497. this.positions[index + 1] = transformed.y;
  36498. this.positions[index + 2] = transformed.z;
  36499. }
  36500. }
  36501. if (this.normals) {
  36502. var normal = BABYLON.Vector3.Zero();
  36503. for (index = 0; index < this.normals.length; index += 3) {
  36504. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36505. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36506. this.normals[index] = transformed.x;
  36507. this.normals[index + 1] = transformed.y;
  36508. this.normals[index + 2] = transformed.z;
  36509. }
  36510. }
  36511. if (this.tangents) {
  36512. var tangent = BABYLON.Vector4.Zero();
  36513. var tangentTransformed = BABYLON.Vector4.Zero();
  36514. for (index = 0; index < this.tangents.length; index += 4) {
  36515. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36516. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36517. this.tangents[index] = tangentTransformed.x;
  36518. this.tangents[index + 1] = tangentTransformed.y;
  36519. this.tangents[index + 2] = tangentTransformed.z;
  36520. this.tangents[index + 3] = tangentTransformed.w;
  36521. }
  36522. }
  36523. if (flip && this.indices) {
  36524. for (index = 0; index < this.indices.length; index += 3) {
  36525. var tmp = this.indices[index + 1];
  36526. this.indices[index + 1] = this.indices[index + 2];
  36527. this.indices[index + 2] = tmp;
  36528. }
  36529. }
  36530. return this;
  36531. };
  36532. /**
  36533. * Merges the passed VertexData into the current one
  36534. * @param other the VertexData to be merged into the current one
  36535. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36536. * @returns the modified VertexData
  36537. */
  36538. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36539. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36540. this._validate();
  36541. other._validate();
  36542. if (!this.normals !== !other.normals ||
  36543. !this.tangents !== !other.tangents ||
  36544. !this.uvs !== !other.uvs ||
  36545. !this.uvs2 !== !other.uvs2 ||
  36546. !this.uvs3 !== !other.uvs3 ||
  36547. !this.uvs4 !== !other.uvs4 ||
  36548. !this.uvs5 !== !other.uvs5 ||
  36549. !this.uvs6 !== !other.uvs6 ||
  36550. !this.colors !== !other.colors ||
  36551. !this.matricesIndices !== !other.matricesIndices ||
  36552. !this.matricesWeights !== !other.matricesWeights ||
  36553. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36554. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36555. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36556. }
  36557. if (other.indices) {
  36558. if (!this.indices) {
  36559. this.indices = [];
  36560. }
  36561. var offset = this.positions ? this.positions.length / 3 : 0;
  36562. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36563. if (isSrcTypedArray) {
  36564. var len = this.indices.length + other.indices.length;
  36565. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36566. temp.set(this.indices);
  36567. var decal = this.indices.length;
  36568. for (var index = 0; index < other.indices.length; index++) {
  36569. temp[decal + index] = other.indices[index] + offset;
  36570. }
  36571. this.indices = temp;
  36572. }
  36573. else {
  36574. for (var index = 0; index < other.indices.length; index++) {
  36575. this.indices.push(other.indices[index] + offset);
  36576. }
  36577. }
  36578. }
  36579. this.positions = this._mergeElement(this.positions, other.positions);
  36580. this.normals = this._mergeElement(this.normals, other.normals);
  36581. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36582. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36583. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36584. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36585. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36586. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36587. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36588. this.colors = this._mergeElement(this.colors, other.colors);
  36589. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36590. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36591. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36592. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36593. return this;
  36594. };
  36595. VertexData.prototype._mergeElement = function (source, other) {
  36596. if (!source) {
  36597. return other;
  36598. }
  36599. if (!other) {
  36600. return source;
  36601. }
  36602. var len = other.length + source.length;
  36603. var isSrcTypedArray = source instanceof Float32Array;
  36604. var isOthTypedArray = other instanceof Float32Array;
  36605. // use non-loop method when the source is Float32Array
  36606. if (isSrcTypedArray) {
  36607. var ret32 = new Float32Array(len);
  36608. ret32.set(source);
  36609. ret32.set(other, source.length);
  36610. return ret32;
  36611. // source is number[], when other is also use concat
  36612. }
  36613. else if (!isOthTypedArray) {
  36614. return source.concat(other);
  36615. // source is a number[], but other is a Float32Array, loop required
  36616. }
  36617. else {
  36618. var ret = source.slice(0); // copy source to a separate array
  36619. for (var i = 0, len = other.length; i < len; i++) {
  36620. ret.push(other[i]);
  36621. }
  36622. return ret;
  36623. }
  36624. };
  36625. VertexData.prototype._validate = function () {
  36626. if (!this.positions) {
  36627. throw new Error("Positions are required");
  36628. }
  36629. var getElementCount = function (kind, values) {
  36630. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36631. if ((values.length % stride) !== 0) {
  36632. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36633. }
  36634. return values.length / stride;
  36635. };
  36636. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36637. var validateElementCount = function (kind, values) {
  36638. var elementCount = getElementCount(kind, values);
  36639. if (elementCount !== positionsElementCount) {
  36640. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36641. }
  36642. };
  36643. if (this.normals)
  36644. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36645. if (this.tangents)
  36646. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36647. if (this.uvs)
  36648. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36649. if (this.uvs2)
  36650. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36651. if (this.uvs3)
  36652. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36653. if (this.uvs4)
  36654. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36655. if (this.uvs5)
  36656. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36657. if (this.uvs6)
  36658. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36659. if (this.colors)
  36660. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36661. if (this.matricesIndices)
  36662. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36663. if (this.matricesWeights)
  36664. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36665. if (this.matricesIndicesExtra)
  36666. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36667. if (this.matricesWeightsExtra)
  36668. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36669. };
  36670. /**
  36671. * Serializes the VertexData
  36672. * @returns a serialized object
  36673. */
  36674. VertexData.prototype.serialize = function () {
  36675. var serializationObject = this.serialize();
  36676. if (this.positions) {
  36677. serializationObject.positions = this.positions;
  36678. }
  36679. if (this.normals) {
  36680. serializationObject.normals = this.normals;
  36681. }
  36682. if (this.tangents) {
  36683. serializationObject.tangents = this.tangents;
  36684. }
  36685. if (this.uvs) {
  36686. serializationObject.uvs = this.uvs;
  36687. }
  36688. if (this.uvs2) {
  36689. serializationObject.uvs2 = this.uvs2;
  36690. }
  36691. if (this.uvs3) {
  36692. serializationObject.uvs3 = this.uvs3;
  36693. }
  36694. if (this.uvs4) {
  36695. serializationObject.uvs4 = this.uvs4;
  36696. }
  36697. if (this.uvs5) {
  36698. serializationObject.uvs5 = this.uvs5;
  36699. }
  36700. if (this.uvs6) {
  36701. serializationObject.uvs6 = this.uvs6;
  36702. }
  36703. if (this.colors) {
  36704. serializationObject.colors = this.colors;
  36705. }
  36706. if (this.matricesIndices) {
  36707. serializationObject.matricesIndices = this.matricesIndices;
  36708. serializationObject.matricesIndices._isExpanded = true;
  36709. }
  36710. if (this.matricesWeights) {
  36711. serializationObject.matricesWeights = this.matricesWeights;
  36712. }
  36713. if (this.matricesIndicesExtra) {
  36714. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36715. serializationObject.matricesIndicesExtra._isExpanded = true;
  36716. }
  36717. if (this.matricesWeightsExtra) {
  36718. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36719. }
  36720. serializationObject.indices = this.indices;
  36721. return serializationObject;
  36722. };
  36723. // Statics
  36724. /**
  36725. * Extracts the vertexData from a mesh
  36726. * @param mesh the mesh from which to extract the VertexData
  36727. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36728. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36729. * @returns the object VertexData associated to the passed mesh
  36730. */
  36731. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36732. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36733. };
  36734. /**
  36735. * Extracts the vertexData from the geometry
  36736. * @param geometry the geometry from which to extract the VertexData
  36737. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36738. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36739. * @returns the object VertexData associated to the passed mesh
  36740. */
  36741. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36742. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36743. };
  36744. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36745. var result = new VertexData();
  36746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36747. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36748. }
  36749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36750. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36751. }
  36752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36753. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36754. }
  36755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36756. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36757. }
  36758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36759. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36760. }
  36761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36762. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36763. }
  36764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36765. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36766. }
  36767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36768. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36769. }
  36770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36771. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36772. }
  36773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36774. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36775. }
  36776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36777. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36778. }
  36779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36780. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36781. }
  36782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36783. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36784. }
  36785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36786. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36787. }
  36788. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36789. return result;
  36790. };
  36791. /**
  36792. * Creates the VertexData for a Ribbon
  36793. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36794. * * pathArray array of paths, each of which an array of successive Vector3
  36795. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36796. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36797. * * 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
  36798. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36799. * * 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)
  36800. * * 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)
  36801. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36802. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36803. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36804. * @returns the VertexData of the ribbon
  36805. */
  36806. VertexData.CreateRibbon = function (options) {
  36807. var pathArray = options.pathArray;
  36808. var closeArray = options.closeArray || false;
  36809. var closePath = options.closePath || false;
  36810. var invertUV = options.invertUV || false;
  36811. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36812. var offset = options.offset || defaultOffset;
  36813. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36815. var customUV = options.uvs;
  36816. var customColors = options.colors;
  36817. var positions = [];
  36818. var indices = [];
  36819. var normals = [];
  36820. var uvs = [];
  36821. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36822. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36823. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36824. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36825. var minlg; // minimal length among all paths from pathArray
  36826. var lg = []; // array of path lengths : nb of vertex per path
  36827. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36828. var p; // path iterator
  36829. var i; // point iterator
  36830. var j; // point iterator
  36831. // if single path in pathArray
  36832. if (pathArray.length < 2) {
  36833. var ar1 = [];
  36834. var ar2 = [];
  36835. for (i = 0; i < pathArray[0].length - offset; i++) {
  36836. ar1.push(pathArray[0][i]);
  36837. ar2.push(pathArray[0][i + offset]);
  36838. }
  36839. pathArray = [ar1, ar2];
  36840. }
  36841. // positions and horizontal distances (u)
  36842. var idc = 0;
  36843. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36844. var path;
  36845. var l;
  36846. minlg = pathArray[0].length;
  36847. var vectlg;
  36848. var dist;
  36849. for (p = 0; p < pathArray.length; p++) {
  36850. uTotalDistance[p] = 0;
  36851. us[p] = [0];
  36852. path = pathArray[p];
  36853. l = path.length;
  36854. minlg = (minlg < l) ? minlg : l;
  36855. j = 0;
  36856. while (j < l) {
  36857. positions.push(path[j].x, path[j].y, path[j].z);
  36858. if (j > 0) {
  36859. vectlg = path[j].subtract(path[j - 1]).length();
  36860. dist = vectlg + uTotalDistance[p];
  36861. us[p].push(dist);
  36862. uTotalDistance[p] = dist;
  36863. }
  36864. j++;
  36865. }
  36866. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36867. j--;
  36868. positions.push(path[0].x, path[0].y, path[0].z);
  36869. vectlg = path[j].subtract(path[0]).length();
  36870. dist = vectlg + uTotalDistance[p];
  36871. us[p].push(dist);
  36872. uTotalDistance[p] = dist;
  36873. }
  36874. lg[p] = l + closePathCorr;
  36875. idx[p] = idc;
  36876. idc += (l + closePathCorr);
  36877. }
  36878. // vertical distances (v)
  36879. var path1;
  36880. var path2;
  36881. var vertex1 = null;
  36882. var vertex2 = null;
  36883. for (i = 0; i < minlg + closePathCorr; i++) {
  36884. vTotalDistance[i] = 0;
  36885. vs[i] = [0];
  36886. for (p = 0; p < pathArray.length - 1; p++) {
  36887. path1 = pathArray[p];
  36888. path2 = pathArray[p + 1];
  36889. if (i === minlg) { // closePath
  36890. vertex1 = path1[0];
  36891. vertex2 = path2[0];
  36892. }
  36893. else {
  36894. vertex1 = path1[i];
  36895. vertex2 = path2[i];
  36896. }
  36897. vectlg = vertex2.subtract(vertex1).length();
  36898. dist = vectlg + vTotalDistance[i];
  36899. vs[i].push(dist);
  36900. vTotalDistance[i] = dist;
  36901. }
  36902. if (closeArray && vertex2 && vertex1) {
  36903. path1 = pathArray[p];
  36904. path2 = pathArray[0];
  36905. if (i === minlg) { // closePath
  36906. vertex2 = path2[0];
  36907. }
  36908. vectlg = vertex2.subtract(vertex1).length();
  36909. dist = vectlg + vTotalDistance[i];
  36910. vTotalDistance[i] = dist;
  36911. }
  36912. }
  36913. // uvs
  36914. var u;
  36915. var v;
  36916. if (customUV) {
  36917. for (p = 0; p < customUV.length; p++) {
  36918. uvs.push(customUV[p].x, customUV[p].y);
  36919. }
  36920. }
  36921. else {
  36922. for (p = 0; p < pathArray.length; p++) {
  36923. for (i = 0; i < minlg + closePathCorr; i++) {
  36924. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36925. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36926. if (invertUV) {
  36927. uvs.push(v, u);
  36928. }
  36929. else {
  36930. uvs.push(u, v);
  36931. }
  36932. }
  36933. }
  36934. }
  36935. // indices
  36936. p = 0; // path index
  36937. var pi = 0; // positions array index
  36938. var l1 = lg[p] - 1; // path1 length
  36939. var l2 = lg[p + 1] - 1; // path2 length
  36940. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36941. var shft = idx[1] - idx[0]; // shift
  36942. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36943. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36944. // 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
  36945. indices.push(pi, pi + shft, pi + 1);
  36946. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36947. pi += 1;
  36948. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36949. p++;
  36950. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36951. shft = idx[0] - idx[p];
  36952. l1 = lg[p] - 1;
  36953. l2 = lg[0] - 1;
  36954. }
  36955. else {
  36956. shft = idx[p + 1] - idx[p];
  36957. l1 = lg[p] - 1;
  36958. l2 = lg[p + 1] - 1;
  36959. }
  36960. pi = idx[p];
  36961. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36962. }
  36963. }
  36964. // normals
  36965. VertexData.ComputeNormals(positions, indices, normals);
  36966. if (closePath) { // update both the first and last vertex normals to their average value
  36967. var indexFirst = 0;
  36968. var indexLast = 0;
  36969. for (p = 0; p < pathArray.length; p++) {
  36970. indexFirst = idx[p] * 3;
  36971. if (p + 1 < pathArray.length) {
  36972. indexLast = (idx[p + 1] - 1) * 3;
  36973. }
  36974. else {
  36975. indexLast = normals.length - 3;
  36976. }
  36977. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36978. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36979. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36980. normals[indexLast] = normals[indexFirst];
  36981. normals[indexLast + 1] = normals[indexFirst + 1];
  36982. normals[indexLast + 2] = normals[indexFirst + 2];
  36983. }
  36984. }
  36985. // sides
  36986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36987. // Colors
  36988. var colors = null;
  36989. if (customColors) {
  36990. colors = new Float32Array(customColors.length * 4);
  36991. for (var c = 0; c < customColors.length; c++) {
  36992. colors[c * 4] = customColors[c].r;
  36993. colors[c * 4 + 1] = customColors[c].g;
  36994. colors[c * 4 + 2] = customColors[c].b;
  36995. colors[c * 4 + 3] = customColors[c].a;
  36996. }
  36997. }
  36998. // Result
  36999. var vertexData = new VertexData();
  37000. var positions32 = new Float32Array(positions);
  37001. var normals32 = new Float32Array(normals);
  37002. var uvs32 = new Float32Array(uvs);
  37003. vertexData.indices = indices;
  37004. vertexData.positions = positions32;
  37005. vertexData.normals = normals32;
  37006. vertexData.uvs = uvs32;
  37007. if (colors) {
  37008. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37009. }
  37010. if (closePath) {
  37011. vertexData._idx = idx;
  37012. }
  37013. return vertexData;
  37014. };
  37015. /**
  37016. * Creates the VertexData for a box
  37017. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37018. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37019. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37020. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37021. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37022. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37023. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37024. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37025. * * 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)
  37026. * * 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)
  37027. * @returns the VertexData of the box
  37028. */
  37029. VertexData.CreateBox = function (options) {
  37030. var normalsSource = [
  37031. new BABYLON.Vector3(0, 0, 1),
  37032. new BABYLON.Vector3(0, 0, -1),
  37033. new BABYLON.Vector3(1, 0, 0),
  37034. new BABYLON.Vector3(-1, 0, 0),
  37035. new BABYLON.Vector3(0, 1, 0),
  37036. new BABYLON.Vector3(0, -1, 0)
  37037. ];
  37038. var indices = [];
  37039. var positions = [];
  37040. var normals = [];
  37041. var uvs = [];
  37042. var width = options.width || options.size || 1;
  37043. var height = options.height || options.size || 1;
  37044. var depth = options.depth || options.size || 1;
  37045. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37046. var faceUV = options.faceUV || new Array(6);
  37047. var faceColors = options.faceColors;
  37048. var colors = [];
  37049. // default face colors and UV if undefined
  37050. for (var f = 0; f < 6; f++) {
  37051. if (faceUV[f] === undefined) {
  37052. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37053. }
  37054. if (faceColors && faceColors[f] === undefined) {
  37055. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37056. }
  37057. }
  37058. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37059. // Create each face in turn.
  37060. for (var index = 0; index < normalsSource.length; index++) {
  37061. var normal = normalsSource[index];
  37062. // Get two vectors perpendicular to the face normal and to each other.
  37063. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37064. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37065. // Six indices (two triangles) per face.
  37066. var verticesLength = positions.length / 3;
  37067. indices.push(verticesLength);
  37068. indices.push(verticesLength + 1);
  37069. indices.push(verticesLength + 2);
  37070. indices.push(verticesLength);
  37071. indices.push(verticesLength + 2);
  37072. indices.push(verticesLength + 3);
  37073. // Four vertices per face.
  37074. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37075. positions.push(vertex.x, vertex.y, vertex.z);
  37076. normals.push(normal.x, normal.y, normal.z);
  37077. uvs.push(faceUV[index].z, faceUV[index].w);
  37078. if (faceColors) {
  37079. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37080. }
  37081. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37082. positions.push(vertex.x, vertex.y, vertex.z);
  37083. normals.push(normal.x, normal.y, normal.z);
  37084. uvs.push(faceUV[index].x, faceUV[index].w);
  37085. if (faceColors) {
  37086. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37087. }
  37088. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37089. positions.push(vertex.x, vertex.y, vertex.z);
  37090. normals.push(normal.x, normal.y, normal.z);
  37091. uvs.push(faceUV[index].x, faceUV[index].y);
  37092. if (faceColors) {
  37093. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37094. }
  37095. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37096. positions.push(vertex.x, vertex.y, vertex.z);
  37097. normals.push(normal.x, normal.y, normal.z);
  37098. uvs.push(faceUV[index].z, faceUV[index].y);
  37099. if (faceColors) {
  37100. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37101. }
  37102. }
  37103. // sides
  37104. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37105. // Result
  37106. var vertexData = new VertexData();
  37107. vertexData.indices = indices;
  37108. vertexData.positions = positions;
  37109. vertexData.normals = normals;
  37110. vertexData.uvs = uvs;
  37111. if (faceColors) {
  37112. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37113. vertexData.colors = totalColors;
  37114. }
  37115. return vertexData;
  37116. };
  37117. /**
  37118. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37119. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37120. * * segments sets the number of horizontal strips optional, default 32
  37121. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37122. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37123. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37124. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37125. * * 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
  37126. * * 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
  37127. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37128. * * 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)
  37129. * * 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)
  37130. * @returns the VertexData of the ellipsoid
  37131. */
  37132. VertexData.CreateSphere = function (options) {
  37133. var segments = options.segments || 32;
  37134. var diameterX = options.diameterX || options.diameter || 1;
  37135. var diameterY = options.diameterY || options.diameter || 1;
  37136. var diameterZ = options.diameterZ || options.diameter || 1;
  37137. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37138. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37139. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37140. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37141. var totalZRotationSteps = 2 + segments;
  37142. var totalYRotationSteps = 2 * totalZRotationSteps;
  37143. var indices = [];
  37144. var positions = [];
  37145. var normals = [];
  37146. var uvs = [];
  37147. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37148. var normalizedZ = zRotationStep / totalZRotationSteps;
  37149. var angleZ = normalizedZ * Math.PI * slice;
  37150. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37151. var normalizedY = yRotationStep / totalYRotationSteps;
  37152. var angleY = normalizedY * Math.PI * 2 * arc;
  37153. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37154. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37155. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37156. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37157. var vertex = complete.multiply(radius);
  37158. var normal = complete.divide(radius).normalize();
  37159. positions.push(vertex.x, vertex.y, vertex.z);
  37160. normals.push(normal.x, normal.y, normal.z);
  37161. uvs.push(normalizedY, normalizedZ);
  37162. }
  37163. if (zRotationStep > 0) {
  37164. var verticesCount = positions.length / 3;
  37165. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37166. indices.push((firstIndex));
  37167. indices.push((firstIndex + 1));
  37168. indices.push(firstIndex + totalYRotationSteps + 1);
  37169. indices.push((firstIndex + totalYRotationSteps + 1));
  37170. indices.push((firstIndex + 1));
  37171. indices.push((firstIndex + totalYRotationSteps + 2));
  37172. }
  37173. }
  37174. }
  37175. // Sides
  37176. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37177. // Result
  37178. var vertexData = new VertexData();
  37179. vertexData.indices = indices;
  37180. vertexData.positions = positions;
  37181. vertexData.normals = normals;
  37182. vertexData.uvs = uvs;
  37183. return vertexData;
  37184. };
  37185. /**
  37186. * Creates the VertexData for a cylinder, cone or prism
  37187. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37188. * * height sets the height (y direction) of the cylinder, optional, default 2
  37189. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37190. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37191. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37192. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37193. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37194. * * 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
  37195. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37196. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37197. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37198. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37199. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37200. * * 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)
  37201. * * 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)
  37202. * @returns the VertexData of the cylinder, cone or prism
  37203. */
  37204. VertexData.CreateCylinder = function (options) {
  37205. var height = options.height || 2;
  37206. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37207. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37208. var tessellation = options.tessellation || 24;
  37209. var subdivisions = options.subdivisions || 1;
  37210. var hasRings = options.hasRings ? true : false;
  37211. var enclose = options.enclose ? true : false;
  37212. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37214. var faceUV = options.faceUV || new Array(3);
  37215. var faceColors = options.faceColors;
  37216. // default face colors and UV if undefined
  37217. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37218. var ringNb = (hasRings) ? subdivisions : 1;
  37219. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37220. var f;
  37221. for (f = 0; f < surfaceNb; f++) {
  37222. if (faceColors && faceColors[f] === undefined) {
  37223. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37224. }
  37225. }
  37226. for (f = 0; f < surfaceNb; f++) {
  37227. if (faceUV && faceUV[f] === undefined) {
  37228. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37229. }
  37230. }
  37231. var indices = new Array();
  37232. var positions = new Array();
  37233. var normals = new Array();
  37234. var uvs = new Array();
  37235. var colors = new Array();
  37236. var angle_step = Math.PI * 2 * arc / tessellation;
  37237. var angle;
  37238. var h;
  37239. var radius;
  37240. var tan = (diameterBottom - diameterTop) / 2 / height;
  37241. var ringVertex = BABYLON.Vector3.Zero();
  37242. var ringNormal = BABYLON.Vector3.Zero();
  37243. var ringFirstVertex = BABYLON.Vector3.Zero();
  37244. var ringFirstNormal = BABYLON.Vector3.Zero();
  37245. var quadNormal = BABYLON.Vector3.Zero();
  37246. var Y = BABYLON.Axis.Y;
  37247. // positions, normals, uvs
  37248. var i;
  37249. var j;
  37250. var r;
  37251. var ringIdx = 1;
  37252. var s = 1; // surface index
  37253. var cs = 0;
  37254. var v = 0;
  37255. for (i = 0; i <= subdivisions; i++) {
  37256. h = i / subdivisions;
  37257. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37258. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37259. for (r = 0; r < ringIdx; r++) {
  37260. if (hasRings) {
  37261. s += r;
  37262. }
  37263. if (enclose) {
  37264. s += 2 * r;
  37265. }
  37266. for (j = 0; j <= tessellation; j++) {
  37267. angle = j * angle_step;
  37268. // position
  37269. ringVertex.x = Math.cos(-angle) * radius;
  37270. ringVertex.y = -height / 2 + h * height;
  37271. ringVertex.z = Math.sin(-angle) * radius;
  37272. // normal
  37273. if (diameterTop === 0 && i === subdivisions) {
  37274. // if no top cap, reuse former normals
  37275. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37276. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37277. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37278. }
  37279. else {
  37280. ringNormal.x = ringVertex.x;
  37281. ringNormal.z = ringVertex.z;
  37282. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37283. ringNormal.normalize();
  37284. }
  37285. // keep first ring vertex values for enclose
  37286. if (j === 0) {
  37287. ringFirstVertex.copyFrom(ringVertex);
  37288. ringFirstNormal.copyFrom(ringNormal);
  37289. }
  37290. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37291. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37292. if (hasRings) {
  37293. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37294. }
  37295. else {
  37296. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37297. }
  37298. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37299. if (faceColors) {
  37300. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37301. }
  37302. }
  37303. // if enclose, add four vertices and their dedicated normals
  37304. if (arc !== 1 && enclose) {
  37305. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37306. positions.push(0, ringVertex.y, 0);
  37307. positions.push(0, ringVertex.y, 0);
  37308. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37309. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37310. quadNormal.normalize();
  37311. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37312. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37313. quadNormal.normalize();
  37314. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37315. if (hasRings) {
  37316. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37317. }
  37318. else {
  37319. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37320. }
  37321. uvs.push(faceUV[s + 1].x, v);
  37322. uvs.push(faceUV[s + 1].z, v);
  37323. if (hasRings) {
  37324. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37325. }
  37326. else {
  37327. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37328. }
  37329. uvs.push(faceUV[s + 2].x, v);
  37330. uvs.push(faceUV[s + 2].z, v);
  37331. if (faceColors) {
  37332. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37333. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37334. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37335. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37336. }
  37337. }
  37338. if (cs !== s) {
  37339. cs = s;
  37340. }
  37341. }
  37342. }
  37343. // indices
  37344. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37345. var s;
  37346. i = 0;
  37347. for (s = 0; s < subdivisions; s++) {
  37348. var i0 = 0;
  37349. var i1 = 0;
  37350. var i2 = 0;
  37351. var i3 = 0;
  37352. for (j = 0; j < tessellation; j++) {
  37353. i0 = i * (e + 1) + j;
  37354. i1 = (i + 1) * (e + 1) + j;
  37355. i2 = i * (e + 1) + (j + 1);
  37356. i3 = (i + 1) * (e + 1) + (j + 1);
  37357. indices.push(i0, i1, i2);
  37358. indices.push(i3, i2, i1);
  37359. }
  37360. if (arc !== 1 && enclose) { // if enclose, add two quads
  37361. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37362. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37363. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37364. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37365. }
  37366. i = (hasRings) ? (i + 2) : (i + 1);
  37367. }
  37368. // Caps
  37369. var createCylinderCap = function (isTop) {
  37370. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37371. if (radius === 0) {
  37372. return;
  37373. }
  37374. // Cap positions, normals & uvs
  37375. var angle;
  37376. var circleVector;
  37377. var i;
  37378. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37379. var c = null;
  37380. if (faceColors) {
  37381. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37382. }
  37383. // cap center
  37384. var vbase = positions.length / 3;
  37385. var offset = isTop ? height / 2 : -height / 2;
  37386. var center = new BABYLON.Vector3(0, offset, 0);
  37387. positions.push(center.x, center.y, center.z);
  37388. normals.push(0, isTop ? 1 : -1, 0);
  37389. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37390. if (c) {
  37391. colors.push(c.r, c.g, c.b, c.a);
  37392. }
  37393. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37394. for (i = 0; i <= tessellation; i++) {
  37395. angle = Math.PI * 2 * i * arc / tessellation;
  37396. var cos = Math.cos(-angle);
  37397. var sin = Math.sin(-angle);
  37398. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37399. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37400. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37401. normals.push(0, isTop ? 1 : -1, 0);
  37402. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37403. if (c) {
  37404. colors.push(c.r, c.g, c.b, c.a);
  37405. }
  37406. }
  37407. // Cap indices
  37408. for (i = 0; i < tessellation; i++) {
  37409. if (!isTop) {
  37410. indices.push(vbase);
  37411. indices.push(vbase + (i + 1));
  37412. indices.push(vbase + (i + 2));
  37413. }
  37414. else {
  37415. indices.push(vbase);
  37416. indices.push(vbase + (i + 2));
  37417. indices.push(vbase + (i + 1));
  37418. }
  37419. }
  37420. };
  37421. // add caps to geometry
  37422. createCylinderCap(false);
  37423. createCylinderCap(true);
  37424. // Sides
  37425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37426. var vertexData = new VertexData();
  37427. vertexData.indices = indices;
  37428. vertexData.positions = positions;
  37429. vertexData.normals = normals;
  37430. vertexData.uvs = uvs;
  37431. if (faceColors) {
  37432. vertexData.colors = colors;
  37433. }
  37434. return vertexData;
  37435. };
  37436. /**
  37437. * Creates the VertexData for a torus
  37438. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37439. * * diameter the diameter of the torus, optional default 1
  37440. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37441. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37442. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37443. * * 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)
  37444. * * 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)
  37445. * @returns the VertexData of the torus
  37446. */
  37447. VertexData.CreateTorus = function (options) {
  37448. var indices = [];
  37449. var positions = [];
  37450. var normals = [];
  37451. var uvs = [];
  37452. var diameter = options.diameter || 1;
  37453. var thickness = options.thickness || 0.5;
  37454. var tessellation = options.tessellation || 16;
  37455. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37456. var stride = tessellation + 1;
  37457. for (var i = 0; i <= tessellation; i++) {
  37458. var u = i / tessellation;
  37459. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37460. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37461. for (var j = 0; j <= tessellation; j++) {
  37462. var v = 1 - j / tessellation;
  37463. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37464. var dx = Math.cos(innerAngle);
  37465. var dy = Math.sin(innerAngle);
  37466. // Create a vertex.
  37467. var normal = new BABYLON.Vector3(dx, dy, 0);
  37468. var position = normal.scale(thickness / 2);
  37469. var textureCoordinate = new BABYLON.Vector2(u, v);
  37470. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37471. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37472. positions.push(position.x, position.y, position.z);
  37473. normals.push(normal.x, normal.y, normal.z);
  37474. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37475. // And create indices for two triangles.
  37476. var nextI = (i + 1) % stride;
  37477. var nextJ = (j + 1) % stride;
  37478. indices.push(i * stride + j);
  37479. indices.push(i * stride + nextJ);
  37480. indices.push(nextI * stride + j);
  37481. indices.push(i * stride + nextJ);
  37482. indices.push(nextI * stride + nextJ);
  37483. indices.push(nextI * stride + j);
  37484. }
  37485. }
  37486. // Sides
  37487. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37488. // Result
  37489. var vertexData = new VertexData();
  37490. vertexData.indices = indices;
  37491. vertexData.positions = positions;
  37492. vertexData.normals = normals;
  37493. vertexData.uvs = uvs;
  37494. return vertexData;
  37495. };
  37496. /**
  37497. * Creates the VertexData of the LineSystem
  37498. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37499. * - lines an array of lines, each line being an array of successive Vector3
  37500. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37501. * @returns the VertexData of the LineSystem
  37502. */
  37503. VertexData.CreateLineSystem = function (options) {
  37504. var indices = [];
  37505. var positions = [];
  37506. var lines = options.lines;
  37507. var colors = options.colors;
  37508. var vertexColors = [];
  37509. var idx = 0;
  37510. for (var l = 0; l < lines.length; l++) {
  37511. var points = lines[l];
  37512. for (var index = 0; index < points.length; index++) {
  37513. positions.push(points[index].x, points[index].y, points[index].z);
  37514. if (colors) {
  37515. var color = colors[l];
  37516. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37517. }
  37518. if (index > 0) {
  37519. indices.push(idx - 1);
  37520. indices.push(idx);
  37521. }
  37522. idx++;
  37523. }
  37524. }
  37525. var vertexData = new VertexData();
  37526. vertexData.indices = indices;
  37527. vertexData.positions = positions;
  37528. if (colors) {
  37529. vertexData.colors = vertexColors;
  37530. }
  37531. return vertexData;
  37532. };
  37533. /**
  37534. * Create the VertexData for a DashedLines
  37535. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37536. * - points an array successive Vector3
  37537. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37538. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37539. * - dashNb the intended total number of dashes, optional, default 200
  37540. * @returns the VertexData for the DashedLines
  37541. */
  37542. VertexData.CreateDashedLines = function (options) {
  37543. var dashSize = options.dashSize || 3;
  37544. var gapSize = options.gapSize || 1;
  37545. var dashNb = options.dashNb || 200;
  37546. var points = options.points;
  37547. var positions = new Array();
  37548. var indices = new Array();
  37549. var curvect = BABYLON.Vector3.Zero();
  37550. var lg = 0;
  37551. var nb = 0;
  37552. var shft = 0;
  37553. var dashshft = 0;
  37554. var curshft = 0;
  37555. var idx = 0;
  37556. var i = 0;
  37557. for (i = 0; i < points.length - 1; i++) {
  37558. points[i + 1].subtractToRef(points[i], curvect);
  37559. lg += curvect.length();
  37560. }
  37561. shft = lg / dashNb;
  37562. dashshft = dashSize * shft / (dashSize + gapSize);
  37563. for (i = 0; i < points.length - 1; i++) {
  37564. points[i + 1].subtractToRef(points[i], curvect);
  37565. nb = Math.floor(curvect.length() / shft);
  37566. curvect.normalize();
  37567. for (var j = 0; j < nb; j++) {
  37568. curshft = shft * j;
  37569. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37570. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37571. indices.push(idx, idx + 1);
  37572. idx += 2;
  37573. }
  37574. }
  37575. // Result
  37576. var vertexData = new VertexData();
  37577. vertexData.positions = positions;
  37578. vertexData.indices = indices;
  37579. return vertexData;
  37580. };
  37581. /**
  37582. * Creates the VertexData for a Ground
  37583. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37584. * - width the width (x direction) of the ground, optional, default 1
  37585. * - height the height (z direction) of the ground, optional, default 1
  37586. * - subdivisions the number of subdivisions per side, optional, default 1
  37587. * @returns the VertexData of the Ground
  37588. */
  37589. VertexData.CreateGround = function (options) {
  37590. var indices = [];
  37591. var positions = [];
  37592. var normals = [];
  37593. var uvs = [];
  37594. var row, col;
  37595. var width = options.width || 1;
  37596. var height = options.height || 1;
  37597. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37598. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37599. for (row = 0; row <= subdivisionsY; row++) {
  37600. for (col = 0; col <= subdivisionsX; col++) {
  37601. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37602. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37603. positions.push(position.x, position.y, position.z);
  37604. normals.push(normal.x, normal.y, normal.z);
  37605. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37606. }
  37607. }
  37608. for (row = 0; row < subdivisionsY; row++) {
  37609. for (col = 0; col < subdivisionsX; col++) {
  37610. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37611. indices.push(col + 1 + row * (subdivisionsX + 1));
  37612. indices.push(col + row * (subdivisionsX + 1));
  37613. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37614. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37615. indices.push(col + row * (subdivisionsX + 1));
  37616. }
  37617. }
  37618. // Result
  37619. var vertexData = new VertexData();
  37620. vertexData.indices = indices;
  37621. vertexData.positions = positions;
  37622. vertexData.normals = normals;
  37623. vertexData.uvs = uvs;
  37624. return vertexData;
  37625. };
  37626. /**
  37627. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37628. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37629. * * xmin the ground minimum X coordinate, optional, default -1
  37630. * * zmin the ground minimum Z coordinate, optional, default -1
  37631. * * xmax the ground maximum X coordinate, optional, default 1
  37632. * * zmax the ground maximum Z coordinate, optional, default 1
  37633. * * 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}
  37634. * * 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}
  37635. * @returns the VertexData of the TiledGround
  37636. */
  37637. VertexData.CreateTiledGround = function (options) {
  37638. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37639. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37640. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37641. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37642. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37643. var precision = options.precision || { w: 1, h: 1 };
  37644. var indices = new Array();
  37645. var positions = new Array();
  37646. var normals = new Array();
  37647. var uvs = new Array();
  37648. var row, col, tileRow, tileCol;
  37649. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37650. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37651. precision.w = (precision.w < 1) ? 1 : precision.w;
  37652. precision.h = (precision.h < 1) ? 1 : precision.h;
  37653. var tileSize = {
  37654. 'w': (xmax - xmin) / subdivisions.w,
  37655. 'h': (zmax - zmin) / subdivisions.h
  37656. };
  37657. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37658. // Indices
  37659. var base = positions.length / 3;
  37660. var rowLength = precision.w + 1;
  37661. for (row = 0; row < precision.h; row++) {
  37662. for (col = 0; col < precision.w; col++) {
  37663. var square = [
  37664. base + col + row * rowLength,
  37665. base + (col + 1) + row * rowLength,
  37666. base + (col + 1) + (row + 1) * rowLength,
  37667. base + col + (row + 1) * rowLength
  37668. ];
  37669. indices.push(square[1]);
  37670. indices.push(square[2]);
  37671. indices.push(square[3]);
  37672. indices.push(square[0]);
  37673. indices.push(square[1]);
  37674. indices.push(square[3]);
  37675. }
  37676. }
  37677. // Position, normals and uvs
  37678. var position = BABYLON.Vector3.Zero();
  37679. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37680. for (row = 0; row <= precision.h; row++) {
  37681. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37682. for (col = 0; col <= precision.w; col++) {
  37683. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37684. position.y = 0;
  37685. positions.push(position.x, position.y, position.z);
  37686. normals.push(normal.x, normal.y, normal.z);
  37687. uvs.push(col / precision.w, row / precision.h);
  37688. }
  37689. }
  37690. }
  37691. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37692. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37693. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37694. }
  37695. }
  37696. // Result
  37697. var vertexData = new VertexData();
  37698. vertexData.indices = indices;
  37699. vertexData.positions = positions;
  37700. vertexData.normals = normals;
  37701. vertexData.uvs = uvs;
  37702. return vertexData;
  37703. };
  37704. /**
  37705. * Creates the VertexData of the Ground designed from a heightmap
  37706. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37707. * * width the width (x direction) of the ground
  37708. * * height the height (z direction) of the ground
  37709. * * subdivisions the number of subdivisions per side
  37710. * * minHeight the minimum altitude on the ground, optional, default 0
  37711. * * maxHeight the maximum altitude on the ground, optional default 1
  37712. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37713. * * buffer the array holding the image color data
  37714. * * bufferWidth the width of image
  37715. * * bufferHeight the height of image
  37716. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37717. * @returns the VertexData of the Ground designed from a heightmap
  37718. */
  37719. VertexData.CreateGroundFromHeightMap = function (options) {
  37720. var indices = [];
  37721. var positions = [];
  37722. var normals = [];
  37723. var uvs = [];
  37724. var row, col;
  37725. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37726. var alphaFilter = options.alphaFilter || 0.0;
  37727. // Vertices
  37728. for (row = 0; row <= options.subdivisions; row++) {
  37729. for (col = 0; col <= options.subdivisions; col++) {
  37730. 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));
  37731. // Compute height
  37732. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37733. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37734. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37735. var r = options.buffer[pos] / 255.0;
  37736. var g = options.buffer[pos + 1] / 255.0;
  37737. var b = options.buffer[pos + 2] / 255.0;
  37738. var a = options.buffer[pos + 3] / 255.0;
  37739. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37740. // If our alpha channel is not within our filter then we will assign a 'special' height
  37741. // Then when building the indices, we will ignore any vertex that is using the special height
  37742. if (a >= alphaFilter)
  37743. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37744. else {
  37745. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37746. }
  37747. // Add vertex
  37748. positions.push(position.x, position.y, position.z);
  37749. normals.push(0, 0, 0);
  37750. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37751. }
  37752. }
  37753. // Indices
  37754. for (row = 0; row < options.subdivisions; row++) {
  37755. for (col = 0; col < options.subdivisions; col++) {
  37756. // Calculate Indices
  37757. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37758. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37759. var idx3 = (col + row * (options.subdivisions + 1));
  37760. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37761. // Check that all indices are visible (based on our special height)
  37762. // Only display the vertex if all Indices are visible
  37763. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37764. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37765. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37766. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37767. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37768. indices.push(idx1);
  37769. indices.push(idx2);
  37770. indices.push(idx3);
  37771. }
  37772. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37773. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37774. indices.push(idx4);
  37775. indices.push(idx1);
  37776. indices.push(idx3);
  37777. }
  37778. }
  37779. }
  37780. // Normals
  37781. VertexData.ComputeNormals(positions, indices, normals);
  37782. // Result
  37783. var vertexData = new VertexData();
  37784. vertexData.indices = indices;
  37785. vertexData.positions = positions;
  37786. vertexData.normals = normals;
  37787. vertexData.uvs = uvs;
  37788. return vertexData;
  37789. };
  37790. /**
  37791. * Creates the VertexData for a Plane
  37792. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37793. * * size sets the width and height of the plane to the value of size, optional default 1
  37794. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37795. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37796. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37797. * * 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)
  37798. * * 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)
  37799. * @returns the VertexData of the box
  37800. */
  37801. VertexData.CreatePlane = function (options) {
  37802. var indices = [];
  37803. var positions = [];
  37804. var normals = [];
  37805. var uvs = [];
  37806. var width = options.width || options.size || 1;
  37807. var height = options.height || options.size || 1;
  37808. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37809. // Vertices
  37810. var halfWidth = width / 2.0;
  37811. var halfHeight = height / 2.0;
  37812. positions.push(-halfWidth, -halfHeight, 0);
  37813. normals.push(0, 0, -1.0);
  37814. uvs.push(0.0, 0.0);
  37815. positions.push(halfWidth, -halfHeight, 0);
  37816. normals.push(0, 0, -1.0);
  37817. uvs.push(1.0, 0.0);
  37818. positions.push(halfWidth, halfHeight, 0);
  37819. normals.push(0, 0, -1.0);
  37820. uvs.push(1.0, 1.0);
  37821. positions.push(-halfWidth, halfHeight, 0);
  37822. normals.push(0, 0, -1.0);
  37823. uvs.push(0.0, 1.0);
  37824. // Indices
  37825. indices.push(0);
  37826. indices.push(1);
  37827. indices.push(2);
  37828. indices.push(0);
  37829. indices.push(2);
  37830. indices.push(3);
  37831. // Sides
  37832. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37833. // Result
  37834. var vertexData = new VertexData();
  37835. vertexData.indices = indices;
  37836. vertexData.positions = positions;
  37837. vertexData.normals = normals;
  37838. vertexData.uvs = uvs;
  37839. return vertexData;
  37840. };
  37841. /**
  37842. * Creates the VertexData of the Disc or regular Polygon
  37843. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37844. * * radius the radius of the disc, optional default 0.5
  37845. * * tessellation the number of polygon sides, optional, default 64
  37846. * * 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
  37847. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37848. * * 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)
  37849. * * 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)
  37850. * @returns the VertexData of the box
  37851. */
  37852. VertexData.CreateDisc = function (options) {
  37853. var positions = new Array();
  37854. var indices = new Array();
  37855. var normals = new Array();
  37856. var uvs = new Array();
  37857. var radius = options.radius || 0.5;
  37858. var tessellation = options.tessellation || 64;
  37859. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37860. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37861. // positions and uvs
  37862. positions.push(0, 0, 0); // disc center first
  37863. uvs.push(0.5, 0.5);
  37864. var theta = Math.PI * 2 * arc;
  37865. var step = theta / tessellation;
  37866. for (var a = 0; a < theta; a += step) {
  37867. var x = Math.cos(a);
  37868. var y = Math.sin(a);
  37869. var u = (x + 1) / 2;
  37870. var v = (1 - y) / 2;
  37871. positions.push(radius * x, radius * y, 0);
  37872. uvs.push(u, v);
  37873. }
  37874. if (arc === 1) {
  37875. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37876. uvs.push(uvs[2], uvs[3]);
  37877. }
  37878. //indices
  37879. var vertexNb = positions.length / 3;
  37880. for (var i = 1; i < vertexNb - 1; i++) {
  37881. indices.push(i + 1, 0, i);
  37882. }
  37883. // result
  37884. VertexData.ComputeNormals(positions, indices, normals);
  37885. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37886. var vertexData = new VertexData();
  37887. vertexData.indices = indices;
  37888. vertexData.positions = positions;
  37889. vertexData.normals = normals;
  37890. vertexData.uvs = uvs;
  37891. return vertexData;
  37892. };
  37893. /**
  37894. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37895. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37896. * @param polygon a mesh built from polygonTriangulation.build()
  37897. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37898. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37899. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37900. * @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)
  37901. * @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)
  37902. * @returns the VertexData of the Polygon
  37903. */
  37904. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37905. var faceUV = fUV || new Array(3);
  37906. var faceColors = fColors;
  37907. var colors = [];
  37908. // default face colors and UV if undefined
  37909. for (var f = 0; f < 3; f++) {
  37910. if (faceUV[f] === undefined) {
  37911. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37912. }
  37913. if (faceColors && faceColors[f] === undefined) {
  37914. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37915. }
  37916. }
  37917. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37918. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37919. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37920. var indices = polygon.getIndices();
  37921. // set face colours and textures
  37922. var idx = 0;
  37923. var face = 0;
  37924. for (var index = 0; index < normals.length; index += 3) {
  37925. //Edge Face no. 1
  37926. if (Math.abs(normals[index + 1]) < 0.001) {
  37927. face = 1;
  37928. }
  37929. //Top Face no. 0
  37930. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37931. face = 0;
  37932. }
  37933. //Bottom Face no. 2
  37934. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37935. face = 2;
  37936. }
  37937. idx = index / 3;
  37938. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37939. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37940. if (faceColors) {
  37941. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37942. }
  37943. }
  37944. // sides
  37945. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37946. // Result
  37947. var vertexData = new VertexData();
  37948. vertexData.indices = indices;
  37949. vertexData.positions = positions;
  37950. vertexData.normals = normals;
  37951. vertexData.uvs = uvs;
  37952. if (faceColors) {
  37953. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37954. vertexData.colors = totalColors;
  37955. }
  37956. return vertexData;
  37957. };
  37958. /**
  37959. * Creates the VertexData of the IcoSphere
  37960. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37961. * * radius the radius of the IcoSphere, optional default 1
  37962. * * radiusX allows stretching in the x direction, optional, default radius
  37963. * * radiusY allows stretching in the y direction, optional, default radius
  37964. * * radiusZ allows stretching in the z direction, optional, default radius
  37965. * * flat when true creates a flat shaded mesh, optional, default true
  37966. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37967. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37968. * * 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)
  37969. * * 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)
  37970. * @returns the VertexData of the IcoSphere
  37971. */
  37972. VertexData.CreateIcoSphere = function (options) {
  37973. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37974. var radius = options.radius || 1;
  37975. var flat = (options.flat === undefined) ? true : options.flat;
  37976. var subdivisions = options.subdivisions || 4;
  37977. var radiusX = options.radiusX || radius;
  37978. var radiusY = options.radiusY || radius;
  37979. var radiusZ = options.radiusZ || radius;
  37980. var t = (1 + Math.sqrt(5)) / 2;
  37981. // 12 vertex x,y,z
  37982. var ico_vertices = [
  37983. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37984. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37985. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37986. ];
  37987. // index of 3 vertex makes a face of icopshere
  37988. var ico_indices = [
  37989. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37990. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37991. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37992. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37993. ];
  37994. // vertex for uv have aliased position, not for UV
  37995. var vertices_unalias_id = [
  37996. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37997. // vertex alias
  37998. 0,
  37999. 2,
  38000. 3,
  38001. 3,
  38002. 3,
  38003. 4,
  38004. 7,
  38005. 8,
  38006. 9,
  38007. 9,
  38008. 10,
  38009. 11 // 23: B + 12
  38010. ];
  38011. // uv as integer step (not pixels !)
  38012. var ico_vertexuv = [
  38013. 5, 1, 3, 1, 6, 4, 0, 0,
  38014. 5, 3, 4, 2, 2, 2, 4, 0,
  38015. 2, 0, 1, 1, 6, 0, 6, 2,
  38016. // vertex alias (for same vertex on different faces)
  38017. 0, 4,
  38018. 3, 3,
  38019. 4, 4,
  38020. 3, 1,
  38021. 4, 2,
  38022. 4, 4,
  38023. 0, 2,
  38024. 1, 1,
  38025. 2, 2,
  38026. 3, 3,
  38027. 1, 3,
  38028. 2, 4 // 23: B + 12
  38029. ];
  38030. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38031. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38032. // First island of uv mapping
  38033. // v = 4h 3+ 2
  38034. // v = 3h 9+ 4
  38035. // v = 2h 9+ 5 B
  38036. // v = 1h 9 1 0
  38037. // v = 0h 3 8 7 A
  38038. // u = 0 1 2 3 4 5 6 *a
  38039. // Second island of uv mapping
  38040. // v = 4h 0+ B+ 4+
  38041. // v = 3h A+ 2+
  38042. // v = 2h 7+ 6 3+
  38043. // v = 1h 8+ 3+
  38044. // v = 0h
  38045. // u = 0 1 2 3 4 5 6 *a
  38046. // Face layout on texture UV mapping
  38047. // ============
  38048. // \ 4 /\ 16 / ======
  38049. // \ / \ / /\ 11 /
  38050. // \/ 7 \/ / \ /
  38051. // ======= / 10 \/
  38052. // /\ 17 /\ =======
  38053. // / \ / \ \ 15 /\
  38054. // / 8 \/ 12 \ \ / \
  38055. // ============ \/ 6 \
  38056. // \ 18 /\ ============
  38057. // \ / \ \ 5 /\ 0 /
  38058. // \/ 13 \ \ / \ /
  38059. // ======= \/ 1 \/
  38060. // =============
  38061. // /\ 19 /\ 2 /\
  38062. // / \ / \ / \
  38063. // / 14 \/ 9 \/ 3 \
  38064. // ===================
  38065. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38066. var ustep = 138 / 1024;
  38067. var vstep = 239 / 1024;
  38068. var uoffset = 60 / 1024;
  38069. var voffset = 26 / 1024;
  38070. // Second island should have margin, not to touch the first island
  38071. // avoid any borderline artefact in pixel rounding
  38072. var island_u_offset = -40 / 1024;
  38073. var island_v_offset = +20 / 1024;
  38074. // face is either island 0 or 1 :
  38075. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38076. var island = [
  38077. 0, 0, 0, 0, 1,
  38078. 0, 0, 1, 1, 0,
  38079. 0, 0, 1, 1, 0,
  38080. 0, 1, 1, 1, 0 // 15 - 19
  38081. ];
  38082. var indices = new Array();
  38083. var positions = new Array();
  38084. var normals = new Array();
  38085. var uvs = new Array();
  38086. var current_indice = 0;
  38087. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38088. var face_vertex_pos = new Array(3);
  38089. var face_vertex_uv = new Array(3);
  38090. var v012;
  38091. for (v012 = 0; v012 < 3; v012++) {
  38092. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38093. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38094. }
  38095. // create all with normals
  38096. for (var face = 0; face < 20; face++) {
  38097. // 3 vertex per face
  38098. for (v012 = 0; v012 < 3; v012++) {
  38099. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38100. var v_id = ico_indices[3 * face + v012];
  38101. // vertex have 3D position (x,y,z)
  38102. 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]);
  38103. // Normalize to get normal, then scale to radius
  38104. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38105. // uv Coordinates from vertex ID
  38106. 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);
  38107. }
  38108. // Subdivide the face (interpolate pos, norm, uv)
  38109. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38110. // - norm is linear interpolation of vertex corner normal
  38111. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38112. // - uv is linear interpolation
  38113. //
  38114. // Topology is as below for sub-divide by 2
  38115. // vertex shown as v0,v1,v2
  38116. // interp index is i1 to progress in range [v0,v1[
  38117. // interp index is i2 to progress in range [v0,v2[
  38118. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38119. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38120. //
  38121. //
  38122. // i2 v2
  38123. // ^ ^
  38124. // / / \
  38125. // / / \
  38126. // / / \
  38127. // / / (0,1) \
  38128. // / #---------\
  38129. // / / \ (0,0)'/ \
  38130. // / / \ / \
  38131. // / / \ / \
  38132. // / / (0,0) \ / (1,0) \
  38133. // / #---------#---------\
  38134. // v0 v1
  38135. //
  38136. // --------------------> i1
  38137. //
  38138. // interp of (i1,i2):
  38139. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38140. // along i1 : lerp(x0,x1, i1/(S-i2))
  38141. //
  38142. // centroid of triangle is needed to get help normal computation
  38143. // (c1,c2) are used for centroid location
  38144. var interp_vertex = function (i1, i2, c1, c2) {
  38145. // vertex is interpolated from
  38146. // - face_vertex_pos[0..2]
  38147. // - face_vertex_uv[0..2]
  38148. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38149. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38150. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38151. pos_interp.normalize();
  38152. var vertex_normal;
  38153. if (flat) {
  38154. // in flat mode, recalculate normal as face centroid normal
  38155. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38156. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38157. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38158. }
  38159. else {
  38160. // in smooth mode, recalculate normal from each single vertex position
  38161. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38162. }
  38163. // Vertex normal need correction due to X,Y,Z radius scaling
  38164. vertex_normal.x /= radiusX;
  38165. vertex_normal.y /= radiusY;
  38166. vertex_normal.z /= radiusZ;
  38167. vertex_normal.normalize();
  38168. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38169. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38170. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38171. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38172. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38173. uvs.push(uv_interp.x, uv_interp.y);
  38174. // push each vertex has member of a face
  38175. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38176. indices.push(current_indice);
  38177. current_indice++;
  38178. };
  38179. for (var i2 = 0; i2 < subdivisions; i2++) {
  38180. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38181. // face : (i1,i2) for /\ :
  38182. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38183. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38184. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38185. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38186. if (i1 + i2 + 1 < subdivisions) {
  38187. // face : (i1,i2)' for \/ :
  38188. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38189. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38190. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38191. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38192. }
  38193. }
  38194. }
  38195. }
  38196. // Sides
  38197. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38198. // Result
  38199. var vertexData = new VertexData();
  38200. vertexData.indices = indices;
  38201. vertexData.positions = positions;
  38202. vertexData.normals = normals;
  38203. vertexData.uvs = uvs;
  38204. return vertexData;
  38205. };
  38206. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38207. /**
  38208. * Creates the VertexData for a Polyhedron
  38209. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38210. * * type provided types are:
  38211. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38212. * * 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)
  38213. * * size the size of the IcoSphere, optional default 1
  38214. * * sizeX allows stretching in the x direction, optional, default size
  38215. * * sizeY allows stretching in the y direction, optional, default size
  38216. * * sizeZ allows stretching in the z direction, optional, default size
  38217. * * 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
  38218. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38219. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38220. * * flat when true creates a flat shaded mesh, optional, default true
  38221. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38222. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38223. * * 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)
  38224. * * 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)
  38225. * @returns the VertexData of the Polyhedron
  38226. */
  38227. VertexData.CreatePolyhedron = function (options) {
  38228. // provided polyhedron types :
  38229. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38230. // 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)
  38231. var polyhedra = [];
  38232. 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]] };
  38233. 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]] };
  38234. polyhedra[2] = {
  38235. 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]],
  38236. 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]]
  38237. };
  38238. polyhedra[3] = {
  38239. 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]],
  38240. 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]]
  38241. };
  38242. polyhedra[4] = {
  38243. 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]],
  38244. 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]]
  38245. };
  38246. 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]] };
  38247. 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]] };
  38248. 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]] };
  38249. 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]] };
  38250. 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]] };
  38251. 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]] };
  38252. 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]] };
  38253. 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]] };
  38254. 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]] };
  38255. polyhedra[14] = {
  38256. 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]],
  38257. 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]]
  38258. };
  38259. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38260. var size = options.size;
  38261. var sizeX = options.sizeX || size || 1;
  38262. var sizeY = options.sizeY || size || 1;
  38263. var sizeZ = options.sizeZ || size || 1;
  38264. var data = options.custom || polyhedra[type];
  38265. var nbfaces = data.face.length;
  38266. var faceUV = options.faceUV || new Array(nbfaces);
  38267. var faceColors = options.faceColors;
  38268. var flat = (options.flat === undefined) ? true : options.flat;
  38269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38270. var positions = new Array();
  38271. var indices = new Array();
  38272. var normals = new Array();
  38273. var uvs = new Array();
  38274. var colors = new Array();
  38275. var index = 0;
  38276. var faceIdx = 0; // face cursor in the array "indexes"
  38277. var indexes = new Array();
  38278. var i = 0;
  38279. var f = 0;
  38280. var u, v, ang, x, y, tmp;
  38281. // default face colors and UV if undefined
  38282. if (flat) {
  38283. for (f = 0; f < nbfaces; f++) {
  38284. if (faceColors && faceColors[f] === undefined) {
  38285. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38286. }
  38287. if (faceUV && faceUV[f] === undefined) {
  38288. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38289. }
  38290. }
  38291. }
  38292. if (!flat) {
  38293. for (i = 0; i < data.vertex.length; i++) {
  38294. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38295. uvs.push(0, 0);
  38296. }
  38297. for (f = 0; f < nbfaces; f++) {
  38298. for (i = 0; i < data.face[f].length - 2; i++) {
  38299. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38300. }
  38301. }
  38302. }
  38303. else {
  38304. for (f = 0; f < nbfaces; f++) {
  38305. var fl = data.face[f].length; // number of vertices of the current face
  38306. ang = 2 * Math.PI / fl;
  38307. x = 0.5 * Math.tan(ang / 2);
  38308. y = 0.5;
  38309. // positions, uvs, colors
  38310. for (i = 0; i < fl; i++) {
  38311. // positions
  38312. 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);
  38313. indexes.push(index);
  38314. index++;
  38315. // uvs
  38316. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38317. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38318. uvs.push(u, v);
  38319. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38320. y = x * Math.sin(ang) + y * Math.cos(ang);
  38321. x = tmp;
  38322. // colors
  38323. if (faceColors) {
  38324. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38325. }
  38326. }
  38327. // indices from indexes
  38328. for (i = 0; i < fl - 2; i++) {
  38329. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38330. }
  38331. faceIdx += fl;
  38332. }
  38333. }
  38334. VertexData.ComputeNormals(positions, indices, normals);
  38335. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38336. var vertexData = new VertexData();
  38337. vertexData.positions = positions;
  38338. vertexData.indices = indices;
  38339. vertexData.normals = normals;
  38340. vertexData.uvs = uvs;
  38341. if (faceColors && flat) {
  38342. vertexData.colors = colors;
  38343. }
  38344. return vertexData;
  38345. };
  38346. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38347. /**
  38348. * Creates the VertexData for a TorusKnot
  38349. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38350. * * radius the radius of the torus knot, optional, default 2
  38351. * * tube the thickness of the tube, optional, default 0.5
  38352. * * radialSegments the number of sides on each tube segments, optional, default 32
  38353. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38354. * * p the number of windings around the z axis, optional, default 2
  38355. * * q the number of windings around the x axis, optional, default 3
  38356. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38357. * * 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)
  38358. * * 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)
  38359. * @returns the VertexData of the Torus Knot
  38360. */
  38361. VertexData.CreateTorusKnot = function (options) {
  38362. var indices = new Array();
  38363. var positions = new Array();
  38364. var normals = new Array();
  38365. var uvs = new Array();
  38366. var radius = options.radius || 2;
  38367. var tube = options.tube || 0.5;
  38368. var radialSegments = options.radialSegments || 32;
  38369. var tubularSegments = options.tubularSegments || 32;
  38370. var p = options.p || 2;
  38371. var q = options.q || 3;
  38372. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38373. // Helper
  38374. var getPos = function (angle) {
  38375. var cu = Math.cos(angle);
  38376. var su = Math.sin(angle);
  38377. var quOverP = q / p * angle;
  38378. var cs = Math.cos(quOverP);
  38379. var tx = radius * (2 + cs) * 0.5 * cu;
  38380. var ty = radius * (2 + cs) * su * 0.5;
  38381. var tz = radius * Math.sin(quOverP) * 0.5;
  38382. return new BABYLON.Vector3(tx, ty, tz);
  38383. };
  38384. // Vertices
  38385. var i;
  38386. var j;
  38387. for (i = 0; i <= radialSegments; i++) {
  38388. var modI = i % radialSegments;
  38389. var u = modI / radialSegments * 2 * p * Math.PI;
  38390. var p1 = getPos(u);
  38391. var p2 = getPos(u + 0.01);
  38392. var tang = p2.subtract(p1);
  38393. var n = p2.add(p1);
  38394. var bitan = BABYLON.Vector3.Cross(tang, n);
  38395. n = BABYLON.Vector3.Cross(bitan, tang);
  38396. bitan.normalize();
  38397. n.normalize();
  38398. for (j = 0; j < tubularSegments; j++) {
  38399. var modJ = j % tubularSegments;
  38400. var v = modJ / tubularSegments * 2 * Math.PI;
  38401. var cx = -tube * Math.cos(v);
  38402. var cy = tube * Math.sin(v);
  38403. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38404. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38405. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38406. uvs.push(i / radialSegments);
  38407. uvs.push(j / tubularSegments);
  38408. }
  38409. }
  38410. for (i = 0; i < radialSegments; i++) {
  38411. for (j = 0; j < tubularSegments; j++) {
  38412. var jNext = (j + 1) % tubularSegments;
  38413. var a = i * tubularSegments + j;
  38414. var b = (i + 1) * tubularSegments + j;
  38415. var c = (i + 1) * tubularSegments + jNext;
  38416. var d = i * tubularSegments + jNext;
  38417. indices.push(d);
  38418. indices.push(b);
  38419. indices.push(a);
  38420. indices.push(d);
  38421. indices.push(c);
  38422. indices.push(b);
  38423. }
  38424. }
  38425. // Normals
  38426. VertexData.ComputeNormals(positions, indices, normals);
  38427. // Sides
  38428. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38429. // Result
  38430. var vertexData = new VertexData();
  38431. vertexData.indices = indices;
  38432. vertexData.positions = positions;
  38433. vertexData.normals = normals;
  38434. vertexData.uvs = uvs;
  38435. return vertexData;
  38436. };
  38437. // Tools
  38438. /**
  38439. * Compute normals for given positions and indices
  38440. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38441. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38442. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38443. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38444. * * facetNormals : optional array of facet normals (vector3)
  38445. * * facetPositions : optional array of facet positions (vector3)
  38446. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38447. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38448. * * bInfo : optional bounding info, required for facetPartitioning computation
  38449. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38450. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38451. * * useRightHandedSystem: optional boolean to for right handed system computation
  38452. * * depthSort : optional boolean to enable the facet depth sort computation
  38453. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38454. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38455. */
  38456. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38457. // temporary scalar variables
  38458. var index = 0; // facet index
  38459. var p1p2x = 0.0; // p1p2 vector x coordinate
  38460. var p1p2y = 0.0; // p1p2 vector y coordinate
  38461. var p1p2z = 0.0; // p1p2 vector z coordinate
  38462. var p3p2x = 0.0; // p3p2 vector x coordinate
  38463. var p3p2y = 0.0; // p3p2 vector y coordinate
  38464. var p3p2z = 0.0; // p3p2 vector z coordinate
  38465. var faceNormalx = 0.0; // facet normal x coordinate
  38466. var faceNormaly = 0.0; // facet normal y coordinate
  38467. var faceNormalz = 0.0; // facet normal z coordinate
  38468. var length = 0.0; // facet normal length before normalization
  38469. var v1x = 0; // vector1 x index in the positions array
  38470. var v1y = 0; // vector1 y index in the positions array
  38471. var v1z = 0; // vector1 z index in the positions array
  38472. var v2x = 0; // vector2 x index in the positions array
  38473. var v2y = 0; // vector2 y index in the positions array
  38474. var v2z = 0; // vector2 z index in the positions array
  38475. var v3x = 0; // vector3 x index in the positions array
  38476. var v3y = 0; // vector3 y index in the positions array
  38477. var v3z = 0; // vector3 z index in the positions array
  38478. var computeFacetNormals = false;
  38479. var computeFacetPositions = false;
  38480. var computeFacetPartitioning = false;
  38481. var computeDepthSort = false;
  38482. var faceNormalSign = 1;
  38483. var ratio = 0;
  38484. var distanceTo = null;
  38485. if (options) {
  38486. computeFacetNormals = (options.facetNormals) ? true : false;
  38487. computeFacetPositions = (options.facetPositions) ? true : false;
  38488. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38489. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38490. ratio = options.ratio || 0;
  38491. computeDepthSort = (options.depthSort) ? true : false;
  38492. distanceTo = (options.distanceTo);
  38493. if (computeDepthSort) {
  38494. if (distanceTo === undefined) {
  38495. distanceTo = BABYLON.Vector3.Zero();
  38496. }
  38497. var depthSortedFacets = options.depthSortedFacets;
  38498. }
  38499. }
  38500. // facetPartitioning reinit if needed
  38501. var xSubRatio = 0;
  38502. var ySubRatio = 0;
  38503. var zSubRatio = 0;
  38504. var subSq = 0;
  38505. if (computeFacetPartitioning && options && options.bbSize) {
  38506. var ox = 0; // X partitioning index for facet position
  38507. var oy = 0; // Y partinioning index for facet position
  38508. var oz = 0; // Z partinioning index for facet position
  38509. var b1x = 0; // X partitioning index for facet v1 vertex
  38510. var b1y = 0; // Y partitioning index for facet v1 vertex
  38511. var b1z = 0; // z partitioning index for facet v1 vertex
  38512. var b2x = 0; // X partitioning index for facet v2 vertex
  38513. var b2y = 0; // Y partitioning index for facet v2 vertex
  38514. var b2z = 0; // Z partitioning index for facet v2 vertex
  38515. var b3x = 0; // X partitioning index for facet v3 vertex
  38516. var b3y = 0; // Y partitioning index for facet v3 vertex
  38517. var b3z = 0; // Z partitioning index for facet v3 vertex
  38518. var block_idx_o = 0; // facet barycenter block index
  38519. var block_idx_v1 = 0; // v1 vertex block index
  38520. var block_idx_v2 = 0; // v2 vertex block index
  38521. var block_idx_v3 = 0; // v3 vertex block index
  38522. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38523. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38524. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38525. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38526. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38527. subSq = options.subDiv.max * options.subDiv.max;
  38528. options.facetPartitioning.length = 0;
  38529. }
  38530. // reset the normals
  38531. for (index = 0; index < positions.length; index++) {
  38532. normals[index] = 0.0;
  38533. }
  38534. // Loop : 1 indice triplet = 1 facet
  38535. var nbFaces = (indices.length / 3) | 0;
  38536. for (index = 0; index < nbFaces; index++) {
  38537. // get the indexes of the coordinates of each vertex of the facet
  38538. v1x = indices[index * 3] * 3;
  38539. v1y = v1x + 1;
  38540. v1z = v1x + 2;
  38541. v2x = indices[index * 3 + 1] * 3;
  38542. v2y = v2x + 1;
  38543. v2z = v2x + 2;
  38544. v3x = indices[index * 3 + 2] * 3;
  38545. v3y = v3x + 1;
  38546. v3z = v3x + 2;
  38547. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38548. p1p2y = positions[v1y] - positions[v2y];
  38549. p1p2z = positions[v1z] - positions[v2z];
  38550. p3p2x = positions[v3x] - positions[v2x];
  38551. p3p2y = positions[v3y] - positions[v2y];
  38552. p3p2z = positions[v3z] - positions[v2z];
  38553. // compute the face normal with the cross product
  38554. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38555. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38556. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38557. // normalize this normal and store it in the array facetData
  38558. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38559. length = (length === 0) ? 1.0 : length;
  38560. faceNormalx /= length;
  38561. faceNormaly /= length;
  38562. faceNormalz /= length;
  38563. if (computeFacetNormals && options) {
  38564. options.facetNormals[index].x = faceNormalx;
  38565. options.facetNormals[index].y = faceNormaly;
  38566. options.facetNormals[index].z = faceNormalz;
  38567. }
  38568. if (computeFacetPositions && options) {
  38569. // compute and the facet barycenter coordinates in the array facetPositions
  38570. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38571. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38572. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38573. }
  38574. if (computeFacetPartitioning && options) {
  38575. // store the facet indexes in arrays in the main facetPartitioning array :
  38576. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38577. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38578. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38579. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38580. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38581. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38582. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38583. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38584. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38585. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38586. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38587. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38588. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38589. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38590. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38591. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38592. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38593. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38594. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38595. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38596. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38597. // push each facet index in each block containing the vertex
  38598. options.facetPartitioning[block_idx_v1].push(index);
  38599. if (block_idx_v2 != block_idx_v1) {
  38600. options.facetPartitioning[block_idx_v2].push(index);
  38601. }
  38602. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38603. options.facetPartitioning[block_idx_v3].push(index);
  38604. }
  38605. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38606. options.facetPartitioning[block_idx_o].push(index);
  38607. }
  38608. }
  38609. if (computeDepthSort && options && options.facetPositions) {
  38610. var dsf = depthSortedFacets[index];
  38611. dsf.ind = index * 3;
  38612. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38613. }
  38614. // compute the normals anyway
  38615. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38616. normals[v1y] += faceNormaly;
  38617. normals[v1z] += faceNormalz;
  38618. normals[v2x] += faceNormalx;
  38619. normals[v2y] += faceNormaly;
  38620. normals[v2z] += faceNormalz;
  38621. normals[v3x] += faceNormalx;
  38622. normals[v3y] += faceNormaly;
  38623. normals[v3z] += faceNormalz;
  38624. }
  38625. // last normalization of each normal
  38626. for (index = 0; index < normals.length / 3; index++) {
  38627. faceNormalx = normals[index * 3];
  38628. faceNormaly = normals[index * 3 + 1];
  38629. faceNormalz = normals[index * 3 + 2];
  38630. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38631. length = (length === 0) ? 1.0 : length;
  38632. faceNormalx /= length;
  38633. faceNormaly /= length;
  38634. faceNormalz /= length;
  38635. normals[index * 3] = faceNormalx;
  38636. normals[index * 3 + 1] = faceNormaly;
  38637. normals[index * 3 + 2] = faceNormalz;
  38638. }
  38639. };
  38640. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38641. var li = indices.length;
  38642. var ln = normals.length;
  38643. var i;
  38644. var n;
  38645. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38646. switch (sideOrientation) {
  38647. case BABYLON.Mesh.FRONTSIDE:
  38648. // nothing changed
  38649. break;
  38650. case BABYLON.Mesh.BACKSIDE:
  38651. var tmp;
  38652. // indices
  38653. for (i = 0; i < li; i += 3) {
  38654. tmp = indices[i];
  38655. indices[i] = indices[i + 2];
  38656. indices[i + 2] = tmp;
  38657. }
  38658. // normals
  38659. for (n = 0; n < ln; n++) {
  38660. normals[n] = -normals[n];
  38661. }
  38662. break;
  38663. case BABYLON.Mesh.DOUBLESIDE:
  38664. // positions
  38665. var lp = positions.length;
  38666. var l = lp / 3;
  38667. for (var p = 0; p < lp; p++) {
  38668. positions[lp + p] = positions[p];
  38669. }
  38670. // indices
  38671. for (i = 0; i < li; i += 3) {
  38672. indices[i + li] = indices[i + 2] + l;
  38673. indices[i + 1 + li] = indices[i + 1] + l;
  38674. indices[i + 2 + li] = indices[i] + l;
  38675. }
  38676. // normals
  38677. for (n = 0; n < ln; n++) {
  38678. normals[ln + n] = -normals[n];
  38679. }
  38680. // uvs
  38681. var lu = uvs.length;
  38682. var u = 0;
  38683. for (u = 0; u < lu; u++) {
  38684. uvs[u + lu] = uvs[u];
  38685. }
  38686. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38687. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38688. u = 0;
  38689. for (i = 0; i < lu / 2; i++) {
  38690. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38691. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38692. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38693. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38694. u += 2;
  38695. }
  38696. break;
  38697. }
  38698. };
  38699. /**
  38700. * Applies VertexData created from the imported parameters to the geometry
  38701. * @param parsedVertexData the parsed data from an imported file
  38702. * @param geometry the geometry to apply the VertexData to
  38703. */
  38704. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38705. var vertexData = new VertexData();
  38706. // positions
  38707. var positions = parsedVertexData.positions;
  38708. if (positions) {
  38709. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38710. }
  38711. // normals
  38712. var normals = parsedVertexData.normals;
  38713. if (normals) {
  38714. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38715. }
  38716. // tangents
  38717. var tangents = parsedVertexData.tangents;
  38718. if (tangents) {
  38719. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38720. }
  38721. // uvs
  38722. var uvs = parsedVertexData.uvs;
  38723. if (uvs) {
  38724. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38725. }
  38726. // uv2s
  38727. var uv2s = parsedVertexData.uv2s;
  38728. if (uv2s) {
  38729. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38730. }
  38731. // uv3s
  38732. var uv3s = parsedVertexData.uv3s;
  38733. if (uv3s) {
  38734. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38735. }
  38736. // uv4s
  38737. var uv4s = parsedVertexData.uv4s;
  38738. if (uv4s) {
  38739. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38740. }
  38741. // uv5s
  38742. var uv5s = parsedVertexData.uv5s;
  38743. if (uv5s) {
  38744. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38745. }
  38746. // uv6s
  38747. var uv6s = parsedVertexData.uv6s;
  38748. if (uv6s) {
  38749. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38750. }
  38751. // colors
  38752. var colors = parsedVertexData.colors;
  38753. if (colors) {
  38754. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38755. }
  38756. // matricesIndices
  38757. var matricesIndices = parsedVertexData.matricesIndices;
  38758. if (matricesIndices) {
  38759. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38760. }
  38761. // matricesWeights
  38762. var matricesWeights = parsedVertexData.matricesWeights;
  38763. if (matricesWeights) {
  38764. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38765. }
  38766. // indices
  38767. var indices = parsedVertexData.indices;
  38768. if (indices) {
  38769. vertexData.indices = indices;
  38770. }
  38771. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38772. };
  38773. return VertexData;
  38774. }());
  38775. BABYLON.VertexData = VertexData;
  38776. })(BABYLON || (BABYLON = {}));
  38777. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38778. var BABYLON;
  38779. (function (BABYLON) {
  38780. /**
  38781. * Class used to store geometry data (vertex buffers + index buffer)
  38782. */
  38783. var Geometry = /** @class */ (function () {
  38784. /**
  38785. * Creates a new geometry
  38786. * @param id defines the unique ID
  38787. * @param scene defines the hosting scene
  38788. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38789. * @param updatable defines if geometry must be updatable (false by default)
  38790. * @param mesh defines the mesh that will be associated with the geometry
  38791. */
  38792. function Geometry(id, scene, vertexData, updatable, mesh) {
  38793. if (updatable === void 0) { updatable = false; }
  38794. if (mesh === void 0) { mesh = null; }
  38795. /**
  38796. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38797. */
  38798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38799. this._totalVertices = 0;
  38800. this._isDisposed = false;
  38801. this._indexBufferIsUpdatable = false;
  38802. this.id = id;
  38803. this._engine = scene.getEngine();
  38804. this._meshes = [];
  38805. this._scene = scene;
  38806. //Init vertex buffer cache
  38807. this._vertexBuffers = {};
  38808. this._indices = [];
  38809. this._updatable = updatable;
  38810. // vertexData
  38811. if (vertexData) {
  38812. this.setAllVerticesData(vertexData, updatable);
  38813. }
  38814. else {
  38815. this._totalVertices = 0;
  38816. this._indices = [];
  38817. }
  38818. if (this._engine.getCaps().vertexArrayObject) {
  38819. this._vertexArrayObjects = {};
  38820. }
  38821. // applyToMesh
  38822. if (mesh) {
  38823. if (mesh.getClassName() === "LinesMesh") {
  38824. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38825. this._updateExtend();
  38826. }
  38827. this.applyToMesh(mesh);
  38828. mesh.computeWorldMatrix(true);
  38829. }
  38830. }
  38831. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38832. /**
  38833. * 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
  38834. */
  38835. get: function () {
  38836. return this._boundingBias;
  38837. },
  38838. /**
  38839. * 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
  38840. */
  38841. set: function (value) {
  38842. if (this._boundingBias && this._boundingBias.equals(value)) {
  38843. return;
  38844. }
  38845. this._boundingBias = value.clone();
  38846. this._updateBoundingInfo(true, null);
  38847. },
  38848. enumerable: true,
  38849. configurable: true
  38850. });
  38851. /**
  38852. * Static function used to attach a new empty geometry to a mesh
  38853. * @param mesh defines the mesh to attach the geometry to
  38854. * @returns the new {BABYLON.Geometry}
  38855. */
  38856. Geometry.CreateGeometryForMesh = function (mesh) {
  38857. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38858. geometry.applyToMesh(mesh);
  38859. return geometry;
  38860. };
  38861. Object.defineProperty(Geometry.prototype, "extend", {
  38862. /**
  38863. * Gets the current extend of the geometry
  38864. */
  38865. get: function () {
  38866. return this._extend;
  38867. },
  38868. enumerable: true,
  38869. configurable: true
  38870. });
  38871. /**
  38872. * Gets the hosting scene
  38873. * @returns the hosting {BABYLON.Scene}
  38874. */
  38875. Geometry.prototype.getScene = function () {
  38876. return this._scene;
  38877. };
  38878. /**
  38879. * Gets the hosting engine
  38880. * @returns the hosting {BABYLON.Engine}
  38881. */
  38882. Geometry.prototype.getEngine = function () {
  38883. return this._engine;
  38884. };
  38885. /**
  38886. * Defines if the geometry is ready to use
  38887. * @returns true if the geometry is ready to be used
  38888. */
  38889. Geometry.prototype.isReady = function () {
  38890. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38891. };
  38892. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38893. /**
  38894. * Gets a value indicating that the geometry should not be serialized
  38895. */
  38896. get: function () {
  38897. for (var index = 0; index < this._meshes.length; index++) {
  38898. if (!this._meshes[index].doNotSerialize) {
  38899. return false;
  38900. }
  38901. }
  38902. return true;
  38903. },
  38904. enumerable: true,
  38905. configurable: true
  38906. });
  38907. /** @hidden */
  38908. Geometry.prototype._rebuild = function () {
  38909. if (this._vertexArrayObjects) {
  38910. this._vertexArrayObjects = {};
  38911. }
  38912. // Index buffer
  38913. if (this._meshes.length !== 0 && this._indices) {
  38914. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38915. }
  38916. // Vertex buffers
  38917. for (var key in this._vertexBuffers) {
  38918. var vertexBuffer = this._vertexBuffers[key];
  38919. vertexBuffer._rebuild();
  38920. }
  38921. };
  38922. /**
  38923. * Affects all geometry data in one call
  38924. * @param vertexData defines the geometry data
  38925. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38926. */
  38927. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38928. vertexData.applyToGeometry(this, updatable);
  38929. this.notifyUpdate();
  38930. };
  38931. /**
  38932. * Set specific vertex data
  38933. * @param kind defines the data kind (Position, normal, etc...)
  38934. * @param data defines the vertex data to use
  38935. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38936. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38937. */
  38938. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38939. if (updatable === void 0) { updatable = false; }
  38940. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38941. this.setVerticesBuffer(buffer);
  38942. };
  38943. /**
  38944. * Removes a specific vertex data
  38945. * @param kind defines the data kind (Position, normal, etc...)
  38946. */
  38947. Geometry.prototype.removeVerticesData = function (kind) {
  38948. if (this._vertexBuffers[kind]) {
  38949. this._vertexBuffers[kind].dispose();
  38950. delete this._vertexBuffers[kind];
  38951. }
  38952. };
  38953. /**
  38954. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38955. * @param buffer defines the vertex buffer to use
  38956. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38957. */
  38958. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38959. if (totalVertices === void 0) { totalVertices = null; }
  38960. var kind = buffer.getKind();
  38961. if (this._vertexBuffers[kind]) {
  38962. this._vertexBuffers[kind].dispose();
  38963. }
  38964. this._vertexBuffers[kind] = buffer;
  38965. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38966. var data = buffer.getData();
  38967. if (totalVertices != null) {
  38968. this._totalVertices = totalVertices;
  38969. }
  38970. else {
  38971. if (data != null) {
  38972. this._totalVertices = data.length / (buffer.byteStride / 4);
  38973. }
  38974. }
  38975. this._updateExtend(data);
  38976. this._resetPointsArrayCache();
  38977. var meshes = this._meshes;
  38978. var numOfMeshes = meshes.length;
  38979. for (var index = 0; index < numOfMeshes; index++) {
  38980. var mesh = meshes[index];
  38981. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38982. mesh._createGlobalSubMesh(false);
  38983. mesh.computeWorldMatrix(true);
  38984. }
  38985. }
  38986. this.notifyUpdate(kind);
  38987. if (this._vertexArrayObjects) {
  38988. this._disposeVertexArrayObjects();
  38989. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38990. }
  38991. };
  38992. /**
  38993. * Update a specific vertex buffer
  38994. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38995. * It will do nothing if the buffer is not updatable
  38996. * @param kind defines the data kind (Position, normal, etc...)
  38997. * @param data defines the data to use
  38998. * @param offset defines the offset in the target buffer where to store the data
  38999. * @param useBytes set to true if the offset is in bytes
  39000. */
  39001. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39002. if (useBytes === void 0) { useBytes = false; }
  39003. var vertexBuffer = this.getVertexBuffer(kind);
  39004. if (!vertexBuffer) {
  39005. return;
  39006. }
  39007. vertexBuffer.updateDirectly(data, offset, useBytes);
  39008. this.notifyUpdate(kind);
  39009. };
  39010. /**
  39011. * Update a specific vertex buffer
  39012. * This function will create a new buffer if the current one is not updatable
  39013. * @param kind defines the data kind (Position, normal, etc...)
  39014. * @param data defines the data to use
  39015. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39016. */
  39017. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39018. if (updateExtends === void 0) { updateExtends = false; }
  39019. var vertexBuffer = this.getVertexBuffer(kind);
  39020. if (!vertexBuffer) {
  39021. return;
  39022. }
  39023. vertexBuffer.update(data);
  39024. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39025. this._updateBoundingInfo(updateExtends, data);
  39026. }
  39027. this.notifyUpdate(kind);
  39028. };
  39029. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39030. if (updateExtends) {
  39031. this._updateExtend(data);
  39032. }
  39033. var meshes = this._meshes;
  39034. var numOfMeshes = meshes.length;
  39035. this._resetPointsArrayCache();
  39036. for (var index = 0; index < numOfMeshes; index++) {
  39037. var mesh = meshes[index];
  39038. if (updateExtends) {
  39039. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39040. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39041. var subMesh = mesh.subMeshes[subIndex];
  39042. subMesh.refreshBoundingInfo();
  39043. }
  39044. }
  39045. }
  39046. };
  39047. /** @hidden */
  39048. Geometry.prototype._bind = function (effect, indexToBind) {
  39049. if (!effect) {
  39050. return;
  39051. }
  39052. if (indexToBind === undefined) {
  39053. indexToBind = this._indexBuffer;
  39054. }
  39055. var vbs = this.getVertexBuffers();
  39056. if (!vbs) {
  39057. return;
  39058. }
  39059. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39060. this._engine.bindBuffers(vbs, indexToBind, effect);
  39061. return;
  39062. }
  39063. // Using VAO
  39064. if (!this._vertexArrayObjects[effect.key]) {
  39065. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39066. }
  39067. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39068. };
  39069. /**
  39070. * Gets total number of vertices
  39071. * @returns the total number of vertices
  39072. */
  39073. Geometry.prototype.getTotalVertices = function () {
  39074. if (!this.isReady()) {
  39075. return 0;
  39076. }
  39077. return this._totalVertices;
  39078. };
  39079. /**
  39080. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39081. * @param kind defines the data kind (Position, normal, etc...)
  39082. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39083. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39084. * @returns a float array containing vertex data
  39085. */
  39086. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39087. var vertexBuffer = this.getVertexBuffer(kind);
  39088. if (!vertexBuffer) {
  39089. return null;
  39090. }
  39091. var data = vertexBuffer.getData();
  39092. if (!data) {
  39093. return null;
  39094. }
  39095. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39096. var count = this._totalVertices * vertexBuffer.getSize();
  39097. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39098. var copy_1 = new Array(count);
  39099. vertexBuffer.forEach(count, function (value, index) {
  39100. copy_1[index] = value;
  39101. });
  39102. return copy_1;
  39103. }
  39104. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39105. if (data instanceof Array) {
  39106. var offset = vertexBuffer.byteOffset / 4;
  39107. return BABYLON.Tools.Slice(data, offset, offset + count);
  39108. }
  39109. else if (data instanceof ArrayBuffer) {
  39110. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39111. }
  39112. else {
  39113. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39114. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39115. var result = new Float32Array(count);
  39116. var source = new Float32Array(data.buffer, offset, count);
  39117. result.set(source);
  39118. return result;
  39119. }
  39120. return new Float32Array(data.buffer, offset, count);
  39121. }
  39122. }
  39123. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39124. return BABYLON.Tools.Slice(data);
  39125. }
  39126. return data;
  39127. };
  39128. /**
  39129. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39130. * @param kind defines the data kind (Position, normal, etc...)
  39131. * @returns true if the vertex buffer with the specified kind is updatable
  39132. */
  39133. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39134. var vb = this._vertexBuffers[kind];
  39135. if (!vb) {
  39136. return false;
  39137. }
  39138. return vb.isUpdatable();
  39139. };
  39140. /**
  39141. * Gets a specific vertex buffer
  39142. * @param kind defines the data kind (Position, normal, etc...)
  39143. * @returns a {BABYLON.VertexBuffer}
  39144. */
  39145. Geometry.prototype.getVertexBuffer = function (kind) {
  39146. if (!this.isReady()) {
  39147. return null;
  39148. }
  39149. return this._vertexBuffers[kind];
  39150. };
  39151. /**
  39152. * Returns all vertex buffers
  39153. * @return an object holding all vertex buffers indexed by kind
  39154. */
  39155. Geometry.prototype.getVertexBuffers = function () {
  39156. if (!this.isReady()) {
  39157. return null;
  39158. }
  39159. return this._vertexBuffers;
  39160. };
  39161. /**
  39162. * Gets a boolean indicating if specific vertex buffer is present
  39163. * @param kind defines the data kind (Position, normal, etc...)
  39164. * @returns true if data is present
  39165. */
  39166. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39167. if (!this._vertexBuffers) {
  39168. if (this._delayInfo) {
  39169. return this._delayInfo.indexOf(kind) !== -1;
  39170. }
  39171. return false;
  39172. }
  39173. return this._vertexBuffers[kind] !== undefined;
  39174. };
  39175. /**
  39176. * Gets a list of all attached data kinds (Position, normal, etc...)
  39177. * @returns a list of string containing all kinds
  39178. */
  39179. Geometry.prototype.getVerticesDataKinds = function () {
  39180. var result = [];
  39181. var kind;
  39182. if (!this._vertexBuffers && this._delayInfo) {
  39183. for (kind in this._delayInfo) {
  39184. result.push(kind);
  39185. }
  39186. }
  39187. else {
  39188. for (kind in this._vertexBuffers) {
  39189. result.push(kind);
  39190. }
  39191. }
  39192. return result;
  39193. };
  39194. /**
  39195. * Update index buffer
  39196. * @param indices defines the indices to store in the index buffer
  39197. * @param offset defines the offset in the target buffer where to store the data
  39198. */
  39199. Geometry.prototype.updateIndices = function (indices, offset) {
  39200. if (!this._indexBuffer) {
  39201. return;
  39202. }
  39203. if (!this._indexBufferIsUpdatable) {
  39204. this.setIndices(indices, null, true);
  39205. }
  39206. else {
  39207. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39208. }
  39209. };
  39210. /**
  39211. * Creates a new index buffer
  39212. * @param indices defines the indices to store in the index buffer
  39213. * @param totalVertices defines the total number of vertices (could be null)
  39214. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39215. */
  39216. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39217. if (totalVertices === void 0) { totalVertices = null; }
  39218. if (updatable === void 0) { updatable = false; }
  39219. if (this._indexBuffer) {
  39220. this._engine._releaseBuffer(this._indexBuffer);
  39221. }
  39222. this._disposeVertexArrayObjects();
  39223. this._indices = indices;
  39224. this._indexBufferIsUpdatable = updatable;
  39225. if (this._meshes.length !== 0 && this._indices) {
  39226. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39227. }
  39228. if (totalVertices != undefined) { // including null and undefined
  39229. this._totalVertices = totalVertices;
  39230. }
  39231. var meshes = this._meshes;
  39232. var numOfMeshes = meshes.length;
  39233. for (var index = 0; index < numOfMeshes; index++) {
  39234. meshes[index]._createGlobalSubMesh(true);
  39235. }
  39236. this.notifyUpdate();
  39237. };
  39238. /**
  39239. * Return the total number of indices
  39240. * @returns the total number of indices
  39241. */
  39242. Geometry.prototype.getTotalIndices = function () {
  39243. if (!this.isReady()) {
  39244. return 0;
  39245. }
  39246. return this._indices.length;
  39247. };
  39248. /**
  39249. * Gets the index buffer array
  39250. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39251. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39252. * @returns the index buffer array
  39253. */
  39254. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39255. if (!this.isReady()) {
  39256. return null;
  39257. }
  39258. var orig = this._indices;
  39259. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39260. return orig;
  39261. }
  39262. else {
  39263. var len = orig.length;
  39264. var copy = [];
  39265. for (var i = 0; i < len; i++) {
  39266. copy.push(orig[i]);
  39267. }
  39268. return copy;
  39269. }
  39270. };
  39271. /**
  39272. * Gets the index buffer
  39273. * @return the index buffer
  39274. */
  39275. Geometry.prototype.getIndexBuffer = function () {
  39276. if (!this.isReady()) {
  39277. return null;
  39278. }
  39279. return this._indexBuffer;
  39280. };
  39281. /** @hidden */
  39282. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39283. if (effect === void 0) { effect = null; }
  39284. if (!effect || !this._vertexArrayObjects) {
  39285. return;
  39286. }
  39287. if (this._vertexArrayObjects[effect.key]) {
  39288. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39289. delete this._vertexArrayObjects[effect.key];
  39290. }
  39291. };
  39292. /**
  39293. * Release the associated resources for a specific mesh
  39294. * @param mesh defines the source mesh
  39295. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39296. */
  39297. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39298. var meshes = this._meshes;
  39299. var index = meshes.indexOf(mesh);
  39300. if (index === -1) {
  39301. return;
  39302. }
  39303. meshes.splice(index, 1);
  39304. mesh._geometry = null;
  39305. if (meshes.length === 0 && shouldDispose) {
  39306. this.dispose();
  39307. }
  39308. };
  39309. /**
  39310. * Apply current geometry to a given mesh
  39311. * @param mesh defines the mesh to apply geometry to
  39312. */
  39313. Geometry.prototype.applyToMesh = function (mesh) {
  39314. if (mesh._geometry === this) {
  39315. return;
  39316. }
  39317. var previousGeometry = mesh._geometry;
  39318. if (previousGeometry) {
  39319. previousGeometry.releaseForMesh(mesh);
  39320. }
  39321. var meshes = this._meshes;
  39322. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39323. mesh._geometry = this;
  39324. this._scene.pushGeometry(this);
  39325. meshes.push(mesh);
  39326. if (this.isReady()) {
  39327. this._applyToMesh(mesh);
  39328. }
  39329. else {
  39330. mesh._boundingInfo = this._boundingInfo;
  39331. }
  39332. };
  39333. Geometry.prototype._updateExtend = function (data) {
  39334. if (data === void 0) { data = null; }
  39335. if (!data) {
  39336. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39337. }
  39338. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39339. };
  39340. Geometry.prototype._applyToMesh = function (mesh) {
  39341. var numOfMeshes = this._meshes.length;
  39342. // vertexBuffers
  39343. for (var kind in this._vertexBuffers) {
  39344. if (numOfMeshes === 1) {
  39345. this._vertexBuffers[kind].create();
  39346. }
  39347. var buffer = this._vertexBuffers[kind].getBuffer();
  39348. if (buffer)
  39349. buffer.references = numOfMeshes;
  39350. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39351. if (!this._extend) {
  39352. this._updateExtend();
  39353. }
  39354. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39355. mesh._createGlobalSubMesh(false);
  39356. //bounding info was just created again, world matrix should be applied again.
  39357. mesh._updateBoundingInfo();
  39358. }
  39359. }
  39360. // indexBuffer
  39361. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39362. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39363. }
  39364. if (this._indexBuffer) {
  39365. this._indexBuffer.references = numOfMeshes;
  39366. }
  39367. };
  39368. Geometry.prototype.notifyUpdate = function (kind) {
  39369. if (this.onGeometryUpdated) {
  39370. this.onGeometryUpdated(this, kind);
  39371. }
  39372. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39373. var mesh = _a[_i];
  39374. mesh._markSubMeshesAsAttributesDirty();
  39375. }
  39376. };
  39377. /**
  39378. * Load the geometry if it was flagged as delay loaded
  39379. * @param scene defines the hosting scene
  39380. * @param onLoaded defines a callback called when the geometry is loaded
  39381. */
  39382. Geometry.prototype.load = function (scene, onLoaded) {
  39383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39384. return;
  39385. }
  39386. if (this.isReady()) {
  39387. if (onLoaded) {
  39388. onLoaded();
  39389. }
  39390. return;
  39391. }
  39392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39393. this._queueLoad(scene, onLoaded);
  39394. };
  39395. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39396. var _this = this;
  39397. if (!this.delayLoadingFile) {
  39398. return;
  39399. }
  39400. scene._addPendingData(this);
  39401. scene._loadFile(this.delayLoadingFile, function (data) {
  39402. if (!_this._delayLoadingFunction) {
  39403. return;
  39404. }
  39405. _this._delayLoadingFunction(JSON.parse(data), _this);
  39406. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39407. _this._delayInfo = [];
  39408. scene._removePendingData(_this);
  39409. var meshes = _this._meshes;
  39410. var numOfMeshes = meshes.length;
  39411. for (var index = 0; index < numOfMeshes; index++) {
  39412. _this._applyToMesh(meshes[index]);
  39413. }
  39414. if (onLoaded) {
  39415. onLoaded();
  39416. }
  39417. }, undefined, true);
  39418. };
  39419. /**
  39420. * Invert the geometry to move from a right handed system to a left handed one.
  39421. */
  39422. Geometry.prototype.toLeftHanded = function () {
  39423. // Flip faces
  39424. var tIndices = this.getIndices(false);
  39425. if (tIndices != null && tIndices.length > 0) {
  39426. for (var i = 0; i < tIndices.length; i += 3) {
  39427. var tTemp = tIndices[i + 0];
  39428. tIndices[i + 0] = tIndices[i + 2];
  39429. tIndices[i + 2] = tTemp;
  39430. }
  39431. this.setIndices(tIndices);
  39432. }
  39433. // Negate position.z
  39434. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39435. if (tPositions != null && tPositions.length > 0) {
  39436. for (var i = 0; i < tPositions.length; i += 3) {
  39437. tPositions[i + 2] = -tPositions[i + 2];
  39438. }
  39439. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39440. }
  39441. // Negate normal.z
  39442. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39443. if (tNormals != null && tNormals.length > 0) {
  39444. for (var i = 0; i < tNormals.length; i += 3) {
  39445. tNormals[i + 2] = -tNormals[i + 2];
  39446. }
  39447. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39448. }
  39449. };
  39450. // Cache
  39451. /** @hidden */
  39452. Geometry.prototype._resetPointsArrayCache = function () {
  39453. this._positions = null;
  39454. };
  39455. /** @hidden */
  39456. Geometry.prototype._generatePointsArray = function () {
  39457. if (this._positions)
  39458. return true;
  39459. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39460. if (!data || data.length === 0) {
  39461. return false;
  39462. }
  39463. this._positions = [];
  39464. for (var index = 0; index < data.length; index += 3) {
  39465. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39466. }
  39467. return true;
  39468. };
  39469. /**
  39470. * Gets a value indicating if the geometry is disposed
  39471. * @returns true if the geometry was disposed
  39472. */
  39473. Geometry.prototype.isDisposed = function () {
  39474. return this._isDisposed;
  39475. };
  39476. Geometry.prototype._disposeVertexArrayObjects = function () {
  39477. if (this._vertexArrayObjects) {
  39478. for (var kind in this._vertexArrayObjects) {
  39479. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39480. }
  39481. this._vertexArrayObjects = {};
  39482. }
  39483. };
  39484. /**
  39485. * Free all associated resources
  39486. */
  39487. Geometry.prototype.dispose = function () {
  39488. var meshes = this._meshes;
  39489. var numOfMeshes = meshes.length;
  39490. var index;
  39491. for (index = 0; index < numOfMeshes; index++) {
  39492. this.releaseForMesh(meshes[index]);
  39493. }
  39494. this._meshes = [];
  39495. this._disposeVertexArrayObjects();
  39496. for (var kind in this._vertexBuffers) {
  39497. this._vertexBuffers[kind].dispose();
  39498. }
  39499. this._vertexBuffers = {};
  39500. this._totalVertices = 0;
  39501. if (this._indexBuffer) {
  39502. this._engine._releaseBuffer(this._indexBuffer);
  39503. }
  39504. this._indexBuffer = null;
  39505. this._indices = [];
  39506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39507. this.delayLoadingFile = null;
  39508. this._delayLoadingFunction = null;
  39509. this._delayInfo = [];
  39510. this._boundingInfo = null;
  39511. this._scene.removeGeometry(this);
  39512. this._isDisposed = true;
  39513. };
  39514. /**
  39515. * Clone the current geometry into a new geometry
  39516. * @param id defines the unique ID of the new geometry
  39517. * @returns a new geometry object
  39518. */
  39519. Geometry.prototype.copy = function (id) {
  39520. var vertexData = new BABYLON.VertexData();
  39521. vertexData.indices = [];
  39522. var indices = this.getIndices();
  39523. if (indices) {
  39524. for (var index = 0; index < indices.length; index++) {
  39525. vertexData.indices.push(indices[index]);
  39526. }
  39527. }
  39528. var updatable = false;
  39529. var stopChecking = false;
  39530. var kind;
  39531. for (kind in this._vertexBuffers) {
  39532. // using slice() to make a copy of the array and not just reference it
  39533. var data = this.getVerticesData(kind);
  39534. if (data instanceof Float32Array) {
  39535. vertexData.set(new Float32Array(data), kind);
  39536. }
  39537. else {
  39538. vertexData.set(data.slice(0), kind);
  39539. }
  39540. if (!stopChecking) {
  39541. var vb = this.getVertexBuffer(kind);
  39542. if (vb) {
  39543. updatable = vb.isUpdatable();
  39544. stopChecking = !updatable;
  39545. }
  39546. }
  39547. }
  39548. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39549. geometry.delayLoadState = this.delayLoadState;
  39550. geometry.delayLoadingFile = this.delayLoadingFile;
  39551. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39552. for (kind in this._delayInfo) {
  39553. geometry._delayInfo = geometry._delayInfo || [];
  39554. geometry._delayInfo.push(kind);
  39555. }
  39556. // Bounding info
  39557. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39558. return geometry;
  39559. };
  39560. /**
  39561. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39562. * @return a JSON representation of the current geometry data (without the vertices data)
  39563. */
  39564. Geometry.prototype.serialize = function () {
  39565. var serializationObject = {};
  39566. serializationObject.id = this.id;
  39567. serializationObject.updatable = this._updatable;
  39568. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39569. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39570. }
  39571. return serializationObject;
  39572. };
  39573. Geometry.prototype.toNumberArray = function (origin) {
  39574. if (Array.isArray(origin)) {
  39575. return origin;
  39576. }
  39577. else {
  39578. return Array.prototype.slice.call(origin);
  39579. }
  39580. };
  39581. /**
  39582. * Serialize all vertices data into a JSON oject
  39583. * @returns a JSON representation of the current geometry data
  39584. */
  39585. Geometry.prototype.serializeVerticeData = function () {
  39586. var serializationObject = this.serialize();
  39587. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39588. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39589. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39590. serializationObject.positions._updatable = true;
  39591. }
  39592. }
  39593. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39594. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39595. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39596. serializationObject.normals._updatable = true;
  39597. }
  39598. }
  39599. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39600. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39601. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39602. serializationObject.tangets._updatable = true;
  39603. }
  39604. }
  39605. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39606. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39607. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39608. serializationObject.uvs._updatable = true;
  39609. }
  39610. }
  39611. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39612. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39613. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39614. serializationObject.uv2s._updatable = true;
  39615. }
  39616. }
  39617. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39618. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39619. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39620. serializationObject.uv3s._updatable = true;
  39621. }
  39622. }
  39623. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39624. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39625. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39626. serializationObject.uv4s._updatable = true;
  39627. }
  39628. }
  39629. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39630. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39631. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39632. serializationObject.uv5s._updatable = true;
  39633. }
  39634. }
  39635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39636. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39637. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39638. serializationObject.uv6s._updatable = true;
  39639. }
  39640. }
  39641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39642. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39643. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39644. serializationObject.colors._updatable = true;
  39645. }
  39646. }
  39647. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39648. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39649. serializationObject.matricesIndices._isExpanded = true;
  39650. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39651. serializationObject.matricesIndices._updatable = true;
  39652. }
  39653. }
  39654. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39655. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39656. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39657. serializationObject.matricesWeights._updatable = true;
  39658. }
  39659. }
  39660. serializationObject.indices = this.toNumberArray(this.getIndices());
  39661. return serializationObject;
  39662. };
  39663. // Statics
  39664. /**
  39665. * Extracts a clone of a mesh geometry
  39666. * @param mesh defines the source mesh
  39667. * @param id defines the unique ID of the new geometry object
  39668. * @returns the new geometry object
  39669. */
  39670. Geometry.ExtractFromMesh = function (mesh, id) {
  39671. var geometry = mesh._geometry;
  39672. if (!geometry) {
  39673. return null;
  39674. }
  39675. return geometry.copy(id);
  39676. };
  39677. /**
  39678. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39679. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39680. * Be aware Math.random() could cause collisions, but:
  39681. * "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"
  39682. * @returns a string containing a new GUID
  39683. */
  39684. Geometry.RandomId = function () {
  39685. return BABYLON.Tools.RandomId();
  39686. };
  39687. /** @hidden */
  39688. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39689. var scene = mesh.getScene();
  39690. // Geometry
  39691. var geometryId = parsedGeometry.geometryId;
  39692. if (geometryId) {
  39693. var geometry = scene.getGeometryByID(geometryId);
  39694. if (geometry) {
  39695. geometry.applyToMesh(mesh);
  39696. }
  39697. }
  39698. else if (parsedGeometry instanceof ArrayBuffer) {
  39699. var binaryInfo = mesh._binaryInfo;
  39700. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39701. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39702. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39703. }
  39704. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39705. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39707. }
  39708. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39709. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39710. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39711. }
  39712. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39713. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39714. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39715. }
  39716. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39717. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39718. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39719. }
  39720. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39721. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39722. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39723. }
  39724. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39725. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39726. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39727. }
  39728. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39729. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39730. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39731. }
  39732. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39733. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39734. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39735. }
  39736. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39737. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39738. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39739. }
  39740. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39741. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39742. var floatIndices = [];
  39743. for (var i = 0; i < matricesIndicesData.length; i++) {
  39744. var index = matricesIndicesData[i];
  39745. floatIndices.push(index & 0x000000FF);
  39746. floatIndices.push((index & 0x0000FF00) >> 8);
  39747. floatIndices.push((index & 0x00FF0000) >> 16);
  39748. floatIndices.push(index >> 24);
  39749. }
  39750. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39751. }
  39752. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39753. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39754. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39755. }
  39756. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39757. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39758. mesh.setIndices(indicesData, null);
  39759. }
  39760. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39761. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39762. mesh.subMeshes = [];
  39763. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39764. var materialIndex = subMeshesData[(i * 5) + 0];
  39765. var verticesStart = subMeshesData[(i * 5) + 1];
  39766. var verticesCount = subMeshesData[(i * 5) + 2];
  39767. var indexStart = subMeshesData[(i * 5) + 3];
  39768. var indexCount = subMeshesData[(i * 5) + 4];
  39769. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39770. }
  39771. }
  39772. }
  39773. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39774. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39775. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39776. if (parsedGeometry.tangents) {
  39777. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39778. }
  39779. if (parsedGeometry.uvs) {
  39780. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39781. }
  39782. if (parsedGeometry.uvs2) {
  39783. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39784. }
  39785. if (parsedGeometry.uvs3) {
  39786. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39787. }
  39788. if (parsedGeometry.uvs4) {
  39789. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39790. }
  39791. if (parsedGeometry.uvs5) {
  39792. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39793. }
  39794. if (parsedGeometry.uvs6) {
  39795. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39796. }
  39797. if (parsedGeometry.colors) {
  39798. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39799. }
  39800. if (parsedGeometry.matricesIndices) {
  39801. if (!parsedGeometry.matricesIndices._isExpanded) {
  39802. var floatIndices = [];
  39803. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39804. var matricesIndex = parsedGeometry.matricesIndices[i];
  39805. floatIndices.push(matricesIndex & 0x000000FF);
  39806. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39807. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39808. floatIndices.push(matricesIndex >> 24);
  39809. }
  39810. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39811. }
  39812. else {
  39813. delete parsedGeometry.matricesIndices._isExpanded;
  39814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39815. }
  39816. }
  39817. if (parsedGeometry.matricesIndicesExtra) {
  39818. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39819. var floatIndices = [];
  39820. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39821. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39822. floatIndices.push(matricesIndex & 0x000000FF);
  39823. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39824. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39825. floatIndices.push(matricesIndex >> 24);
  39826. }
  39827. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39828. }
  39829. else {
  39830. delete parsedGeometry.matricesIndices._isExpanded;
  39831. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39832. }
  39833. }
  39834. if (parsedGeometry.matricesWeights) {
  39835. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39836. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39837. }
  39838. if (parsedGeometry.matricesWeightsExtra) {
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39840. }
  39841. mesh.setIndices(parsedGeometry.indices, null);
  39842. }
  39843. // SubMeshes
  39844. if (parsedGeometry.subMeshes) {
  39845. mesh.subMeshes = [];
  39846. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39847. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39848. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39849. }
  39850. }
  39851. // Flat shading
  39852. if (mesh._shouldGenerateFlatShading) {
  39853. mesh.convertToFlatShadedMesh();
  39854. delete mesh._shouldGenerateFlatShading;
  39855. }
  39856. // Update
  39857. mesh.computeWorldMatrix(true);
  39858. scene.onMeshImportedObservable.notifyObservers(mesh);
  39859. };
  39860. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39861. var epsilon = 1e-3;
  39862. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39863. return;
  39864. }
  39865. var noInfluenceBoneIndex = 0.0;
  39866. if (parsedGeometry.skeletonId > -1) {
  39867. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39868. if (!skeleton) {
  39869. return;
  39870. }
  39871. noInfluenceBoneIndex = skeleton.bones.length;
  39872. }
  39873. else {
  39874. return;
  39875. }
  39876. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39877. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39878. var matricesWeights = parsedGeometry.matricesWeights;
  39879. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39880. var influencers = parsedGeometry.numBoneInfluencer;
  39881. var size = matricesWeights.length;
  39882. for (var i = 0; i < size; i += 4) {
  39883. var weight = 0.0;
  39884. var firstZeroWeight = -1;
  39885. for (var j = 0; j < 4; j++) {
  39886. var w = matricesWeights[i + j];
  39887. weight += w;
  39888. if (w < epsilon && firstZeroWeight < 0) {
  39889. firstZeroWeight = j;
  39890. }
  39891. }
  39892. if (matricesWeightsExtra) {
  39893. for (var j = 0; j < 4; j++) {
  39894. var w = matricesWeightsExtra[i + j];
  39895. weight += w;
  39896. if (w < epsilon && firstZeroWeight < 0) {
  39897. firstZeroWeight = j + 4;
  39898. }
  39899. }
  39900. }
  39901. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39902. firstZeroWeight = influencers - 1;
  39903. }
  39904. if (weight > epsilon) {
  39905. var mweight = 1.0 / weight;
  39906. for (var j = 0; j < 4; j++) {
  39907. matricesWeights[i + j] *= mweight;
  39908. }
  39909. if (matricesWeightsExtra) {
  39910. for (var j = 0; j < 4; j++) {
  39911. matricesWeightsExtra[i + j] *= mweight;
  39912. }
  39913. }
  39914. }
  39915. else {
  39916. if (firstZeroWeight >= 4) {
  39917. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39918. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39919. }
  39920. else {
  39921. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39922. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39923. }
  39924. }
  39925. }
  39926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39927. if (parsedGeometry.matricesWeightsExtra) {
  39928. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39929. }
  39930. };
  39931. /**
  39932. * Create a new geometry from persisted data (Using .babylon file format)
  39933. * @param parsedVertexData defines the persisted data
  39934. * @param scene defines the hosting scene
  39935. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39936. * @returns the new geometry object
  39937. */
  39938. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39939. if (scene.getGeometryByID(parsedVertexData.id)) {
  39940. return null; // null since geometry could be something else than a box...
  39941. }
  39942. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39943. if (BABYLON.Tags) {
  39944. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39945. }
  39946. if (parsedVertexData.delayLoadingFile) {
  39947. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39948. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39949. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39950. geometry._delayInfo = [];
  39951. if (parsedVertexData.hasUVs) {
  39952. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39953. }
  39954. if (parsedVertexData.hasUVs2) {
  39955. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39956. }
  39957. if (parsedVertexData.hasUVs3) {
  39958. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39959. }
  39960. if (parsedVertexData.hasUVs4) {
  39961. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39962. }
  39963. if (parsedVertexData.hasUVs5) {
  39964. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39965. }
  39966. if (parsedVertexData.hasUVs6) {
  39967. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39968. }
  39969. if (parsedVertexData.hasColors) {
  39970. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39971. }
  39972. if (parsedVertexData.hasMatricesIndices) {
  39973. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39974. }
  39975. if (parsedVertexData.hasMatricesWeights) {
  39976. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39977. }
  39978. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39979. }
  39980. else {
  39981. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39982. }
  39983. scene.pushGeometry(geometry, true);
  39984. return geometry;
  39985. };
  39986. return Geometry;
  39987. }());
  39988. BABYLON.Geometry = Geometry;
  39989. // Primitives
  39990. /// Abstract class
  39991. /**
  39992. * Abstract class used to provide common services for all typed geometries
  39993. * @hidden
  39994. */
  39995. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39996. __extends(_PrimitiveGeometry, _super);
  39997. /**
  39998. * Creates a new typed geometry
  39999. * @param id defines the unique ID of the geometry
  40000. * @param scene defines the hosting scene
  40001. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40002. * @param mesh defines the hosting mesh (can be null)
  40003. */
  40004. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40005. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40006. if (mesh === void 0) { mesh = null; }
  40007. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40008. _this._canBeRegenerated = _canBeRegenerated;
  40009. _this._beingRegenerated = true;
  40010. _this.regenerate();
  40011. _this._beingRegenerated = false;
  40012. return _this;
  40013. }
  40014. /**
  40015. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40016. * @returns true if the geometry can be regenerated
  40017. */
  40018. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40019. return this._canBeRegenerated;
  40020. };
  40021. /**
  40022. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40023. */
  40024. _PrimitiveGeometry.prototype.regenerate = function () {
  40025. if (!this._canBeRegenerated) {
  40026. return;
  40027. }
  40028. this._beingRegenerated = true;
  40029. this.setAllVerticesData(this._regenerateVertexData(), false);
  40030. this._beingRegenerated = false;
  40031. };
  40032. /**
  40033. * Clone the geometry
  40034. * @param id defines the unique ID of the new geometry
  40035. * @returns the new geometry
  40036. */
  40037. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40038. return _super.prototype.copy.call(this, id);
  40039. };
  40040. // overrides
  40041. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40042. if (!this._beingRegenerated) {
  40043. return;
  40044. }
  40045. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40046. };
  40047. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40048. if (!this._beingRegenerated) {
  40049. return;
  40050. }
  40051. _super.prototype.setVerticesData.call(this, kind, data, false);
  40052. };
  40053. // to override
  40054. /** @hidden */
  40055. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40056. throw new Error("Abstract method");
  40057. };
  40058. _PrimitiveGeometry.prototype.copy = function (id) {
  40059. throw new Error("Must be overriden in sub-classes.");
  40060. };
  40061. _PrimitiveGeometry.prototype.serialize = function () {
  40062. var serializationObject = _super.prototype.serialize.call(this);
  40063. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40064. return serializationObject;
  40065. };
  40066. return _PrimitiveGeometry;
  40067. }(Geometry));
  40068. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40069. /**
  40070. * Creates a ribbon geometry
  40071. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40072. */
  40073. var RibbonGeometry = /** @class */ (function (_super) {
  40074. __extends(RibbonGeometry, _super);
  40075. /**
  40076. * Creates a ribbon geometry
  40077. * @param id defines the unique ID of the geometry
  40078. * @param scene defines the hosting scene
  40079. * @param pathArray defines the array of paths to use
  40080. * @param closeArray defines if the last path and the first path must be joined
  40081. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40082. * @param offset defines the offset between points
  40083. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40084. * @param mesh defines the hosting mesh (can be null)
  40085. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40086. */
  40087. function RibbonGeometry(id, scene,
  40088. /**
  40089. * Defines the array of paths to use
  40090. */
  40091. pathArray,
  40092. /**
  40093. * Defines if the last and first points of each path in your pathArray must be joined
  40094. */
  40095. closeArray,
  40096. /**
  40097. * Defines if the last and first points of each path in your pathArray must be joined
  40098. */
  40099. closePath,
  40100. /**
  40101. * Defines the offset between points
  40102. */
  40103. offset, canBeRegenerated, mesh,
  40104. /**
  40105. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40106. */
  40107. side) {
  40108. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40109. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40110. _this.pathArray = pathArray;
  40111. _this.closeArray = closeArray;
  40112. _this.closePath = closePath;
  40113. _this.offset = offset;
  40114. _this.side = side;
  40115. return _this;
  40116. }
  40117. /** @hidden */
  40118. RibbonGeometry.prototype._regenerateVertexData = function () {
  40119. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40120. };
  40121. RibbonGeometry.prototype.copy = function (id) {
  40122. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40123. };
  40124. return RibbonGeometry;
  40125. }(_PrimitiveGeometry));
  40126. BABYLON.RibbonGeometry = RibbonGeometry;
  40127. /**
  40128. * Creates a box geometry
  40129. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40130. */
  40131. var BoxGeometry = /** @class */ (function (_super) {
  40132. __extends(BoxGeometry, _super);
  40133. /**
  40134. * Creates a box geometry
  40135. * @param id defines the unique ID of the geometry
  40136. * @param scene defines the hosting scene
  40137. * @param size defines the zise of the box (width, height and depth are the same)
  40138. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40139. * @param mesh defines the hosting mesh (can be null)
  40140. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40141. */
  40142. function BoxGeometry(id, scene,
  40143. /**
  40144. * Defines the zise of the box (width, height and depth are the same)
  40145. */
  40146. size, canBeRegenerated, mesh,
  40147. /**
  40148. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40149. */
  40150. side) {
  40151. if (mesh === void 0) { mesh = null; }
  40152. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40153. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40154. _this.size = size;
  40155. _this.side = side;
  40156. return _this;
  40157. }
  40158. /** @hidden */
  40159. BoxGeometry.prototype._regenerateVertexData = function () {
  40160. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40161. };
  40162. BoxGeometry.prototype.copy = function (id) {
  40163. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40164. };
  40165. BoxGeometry.prototype.serialize = function () {
  40166. var serializationObject = _super.prototype.serialize.call(this);
  40167. serializationObject.size = this.size;
  40168. return serializationObject;
  40169. };
  40170. BoxGeometry.Parse = function (parsedBox, scene) {
  40171. if (scene.getGeometryByID(parsedBox.id)) {
  40172. return null; // null since geometry could be something else than a box...
  40173. }
  40174. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40175. if (BABYLON.Tags) {
  40176. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40177. }
  40178. scene.pushGeometry(box, true);
  40179. return box;
  40180. };
  40181. return BoxGeometry;
  40182. }(_PrimitiveGeometry));
  40183. BABYLON.BoxGeometry = BoxGeometry;
  40184. /**
  40185. * Creates a sphere geometry
  40186. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40187. */
  40188. var SphereGeometry = /** @class */ (function (_super) {
  40189. __extends(SphereGeometry, _super);
  40190. /**
  40191. * Create a new sphere geometry
  40192. * @param id defines the unique ID of the geometry
  40193. * @param scene defines the hosting scene
  40194. * @param segments defines the number of segments to use to create the sphere
  40195. * @param diameter defines the diameter of the sphere
  40196. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40197. * @param mesh defines the hosting mesh (can be null)
  40198. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40199. */
  40200. function SphereGeometry(id, scene,
  40201. /**
  40202. * Defines the number of segments to use to create the sphere
  40203. */
  40204. segments,
  40205. /**
  40206. * Defines the diameter of the sphere
  40207. */
  40208. diameter, canBeRegenerated, mesh,
  40209. /**
  40210. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40211. */
  40212. side) {
  40213. if (mesh === void 0) { mesh = null; }
  40214. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40216. _this.segments = segments;
  40217. _this.diameter = diameter;
  40218. _this.side = side;
  40219. return _this;
  40220. }
  40221. /** @hidden */
  40222. SphereGeometry.prototype._regenerateVertexData = function () {
  40223. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40224. };
  40225. SphereGeometry.prototype.copy = function (id) {
  40226. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40227. };
  40228. SphereGeometry.prototype.serialize = function () {
  40229. var serializationObject = _super.prototype.serialize.call(this);
  40230. serializationObject.segments = this.segments;
  40231. serializationObject.diameter = this.diameter;
  40232. return serializationObject;
  40233. };
  40234. SphereGeometry.Parse = function (parsedSphere, scene) {
  40235. if (scene.getGeometryByID(parsedSphere.id)) {
  40236. return null; // null since geometry could be something else than a sphere...
  40237. }
  40238. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40239. if (BABYLON.Tags) {
  40240. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40241. }
  40242. scene.pushGeometry(sphere, true);
  40243. return sphere;
  40244. };
  40245. return SphereGeometry;
  40246. }(_PrimitiveGeometry));
  40247. BABYLON.SphereGeometry = SphereGeometry;
  40248. /**
  40249. * Creates a disc geometry
  40250. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40251. */
  40252. var DiscGeometry = /** @class */ (function (_super) {
  40253. __extends(DiscGeometry, _super);
  40254. /**
  40255. * Creates a new disc geometry
  40256. * @param id defines the unique ID of the geometry
  40257. * @param scene defines the hosting scene
  40258. * @param radius defines the radius of the disc
  40259. * @param tessellation defines the tesselation factor to apply to the disc
  40260. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40261. * @param mesh defines the hosting mesh (can be null)
  40262. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40263. */
  40264. function DiscGeometry(id, scene,
  40265. /**
  40266. * Defines the radius of the disc
  40267. */
  40268. radius,
  40269. /**
  40270. * Defines the tesselation factor to apply to the disc
  40271. */
  40272. tessellation, canBeRegenerated, mesh,
  40273. /**
  40274. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40275. */
  40276. side) {
  40277. if (mesh === void 0) { mesh = null; }
  40278. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40279. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40280. _this.radius = radius;
  40281. _this.tessellation = tessellation;
  40282. _this.side = side;
  40283. return _this;
  40284. }
  40285. /** @hidden */
  40286. DiscGeometry.prototype._regenerateVertexData = function () {
  40287. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40288. };
  40289. DiscGeometry.prototype.copy = function (id) {
  40290. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40291. };
  40292. return DiscGeometry;
  40293. }(_PrimitiveGeometry));
  40294. BABYLON.DiscGeometry = DiscGeometry;
  40295. /**
  40296. * Creates a new cylinder geometry
  40297. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40298. */
  40299. var CylinderGeometry = /** @class */ (function (_super) {
  40300. __extends(CylinderGeometry, _super);
  40301. /**
  40302. * Creates a new cylinder geometry
  40303. * @param id defines the unique ID of the geometry
  40304. * @param scene defines the hosting scene
  40305. * @param height defines the height of the cylinder
  40306. * @param diameterTop defines the diameter of the cylinder's top cap
  40307. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40308. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40309. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40310. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40311. * @param mesh defines the hosting mesh (can be null)
  40312. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40313. */
  40314. function CylinderGeometry(id, scene,
  40315. /**
  40316. * Defines the height of the cylinder
  40317. */
  40318. height,
  40319. /**
  40320. * Defines the diameter of the cylinder's top cap
  40321. */
  40322. diameterTop,
  40323. /**
  40324. * Defines the diameter of the cylinder's bottom cap
  40325. */
  40326. diameterBottom,
  40327. /**
  40328. * Defines the tessellation factor to apply to the cylinder
  40329. */
  40330. tessellation,
  40331. /**
  40332. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40333. */
  40334. subdivisions, canBeRegenerated, mesh,
  40335. /**
  40336. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40337. */
  40338. side) {
  40339. if (subdivisions === void 0) { subdivisions = 1; }
  40340. if (mesh === void 0) { mesh = null; }
  40341. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40342. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40343. _this.height = height;
  40344. _this.diameterTop = diameterTop;
  40345. _this.diameterBottom = diameterBottom;
  40346. _this.tessellation = tessellation;
  40347. _this.subdivisions = subdivisions;
  40348. _this.side = side;
  40349. return _this;
  40350. }
  40351. /** @hidden */
  40352. CylinderGeometry.prototype._regenerateVertexData = function () {
  40353. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40354. };
  40355. CylinderGeometry.prototype.copy = function (id) {
  40356. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40357. };
  40358. CylinderGeometry.prototype.serialize = function () {
  40359. var serializationObject = _super.prototype.serialize.call(this);
  40360. serializationObject.height = this.height;
  40361. serializationObject.diameterTop = this.diameterTop;
  40362. serializationObject.diameterBottom = this.diameterBottom;
  40363. serializationObject.tessellation = this.tessellation;
  40364. return serializationObject;
  40365. };
  40366. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40367. if (scene.getGeometryByID(parsedCylinder.id)) {
  40368. return null; // null since geometry could be something else than a cylinder...
  40369. }
  40370. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40371. if (BABYLON.Tags) {
  40372. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40373. }
  40374. scene.pushGeometry(cylinder, true);
  40375. return cylinder;
  40376. };
  40377. return CylinderGeometry;
  40378. }(_PrimitiveGeometry));
  40379. BABYLON.CylinderGeometry = CylinderGeometry;
  40380. /**
  40381. * Creates a new torus geometry
  40382. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40383. */
  40384. var TorusGeometry = /** @class */ (function (_super) {
  40385. __extends(TorusGeometry, _super);
  40386. /**
  40387. * Creates a new torus geometry
  40388. * @param id defines the unique ID of the geometry
  40389. * @param scene defines the hosting scene
  40390. * @param diameter defines the diameter of the torus
  40391. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40392. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40393. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40394. * @param mesh defines the hosting mesh (can be null)
  40395. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40396. */
  40397. function TorusGeometry(id, scene,
  40398. /**
  40399. * Defines the diameter of the torus
  40400. */
  40401. diameter,
  40402. /**
  40403. * Defines the thickness of the torus (ie. internal diameter)
  40404. */
  40405. thickness,
  40406. /**
  40407. * Defines the tesselation factor to apply to the torus
  40408. */
  40409. tessellation, canBeRegenerated, mesh,
  40410. /**
  40411. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40412. */
  40413. side) {
  40414. if (mesh === void 0) { mesh = null; }
  40415. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40416. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40417. _this.diameter = diameter;
  40418. _this.thickness = thickness;
  40419. _this.tessellation = tessellation;
  40420. _this.side = side;
  40421. return _this;
  40422. }
  40423. /** @hidden */
  40424. TorusGeometry.prototype._regenerateVertexData = function () {
  40425. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40426. };
  40427. TorusGeometry.prototype.copy = function (id) {
  40428. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40429. };
  40430. TorusGeometry.prototype.serialize = function () {
  40431. var serializationObject = _super.prototype.serialize.call(this);
  40432. serializationObject.diameter = this.diameter;
  40433. serializationObject.thickness = this.thickness;
  40434. serializationObject.tessellation = this.tessellation;
  40435. return serializationObject;
  40436. };
  40437. TorusGeometry.Parse = function (parsedTorus, scene) {
  40438. if (scene.getGeometryByID(parsedTorus.id)) {
  40439. return null; // null since geometry could be something else than a torus...
  40440. }
  40441. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40442. if (BABYLON.Tags) {
  40443. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40444. }
  40445. scene.pushGeometry(torus, true);
  40446. return torus;
  40447. };
  40448. return TorusGeometry;
  40449. }(_PrimitiveGeometry));
  40450. BABYLON.TorusGeometry = TorusGeometry;
  40451. /**
  40452. * Creates a new ground geometry
  40453. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40454. */
  40455. var GroundGeometry = /** @class */ (function (_super) {
  40456. __extends(GroundGeometry, _super);
  40457. /**
  40458. * Creates a new ground geometry
  40459. * @param id defines the unique ID of the geometry
  40460. * @param scene defines the hosting scene
  40461. * @param width defines the width of the ground
  40462. * @param height defines the height of the ground
  40463. * @param subdivisions defines the subdivisions to apply to the ground
  40464. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40465. * @param mesh defines the hosting mesh (can be null)
  40466. */
  40467. function GroundGeometry(id, scene,
  40468. /**
  40469. * Defines the width of the ground
  40470. */
  40471. width,
  40472. /**
  40473. * Defines the height of the ground
  40474. */
  40475. height,
  40476. /**
  40477. * Defines the subdivisions to apply to the ground
  40478. */
  40479. subdivisions, canBeRegenerated, mesh) {
  40480. if (mesh === void 0) { mesh = null; }
  40481. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40482. _this.width = width;
  40483. _this.height = height;
  40484. _this.subdivisions = subdivisions;
  40485. return _this;
  40486. }
  40487. /** @hidden */
  40488. GroundGeometry.prototype._regenerateVertexData = function () {
  40489. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40490. };
  40491. GroundGeometry.prototype.copy = function (id) {
  40492. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40493. };
  40494. GroundGeometry.prototype.serialize = function () {
  40495. var serializationObject = _super.prototype.serialize.call(this);
  40496. serializationObject.width = this.width;
  40497. serializationObject.height = this.height;
  40498. serializationObject.subdivisions = this.subdivisions;
  40499. return serializationObject;
  40500. };
  40501. GroundGeometry.Parse = function (parsedGround, scene) {
  40502. if (scene.getGeometryByID(parsedGround.id)) {
  40503. return null; // null since geometry could be something else than a ground...
  40504. }
  40505. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40506. if (BABYLON.Tags) {
  40507. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40508. }
  40509. scene.pushGeometry(ground, true);
  40510. return ground;
  40511. };
  40512. return GroundGeometry;
  40513. }(_PrimitiveGeometry));
  40514. BABYLON.GroundGeometry = GroundGeometry;
  40515. /**
  40516. * Creates a tiled ground geometry
  40517. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40518. */
  40519. var TiledGroundGeometry = /** @class */ (function (_super) {
  40520. __extends(TiledGroundGeometry, _super);
  40521. /**
  40522. * Creates a tiled ground geometry
  40523. * @param id defines the unique ID of the geometry
  40524. * @param scene defines the hosting scene
  40525. * @param xmin defines the minimum value on X axis
  40526. * @param zmin defines the minimum value on Z axis
  40527. * @param xmax defines the maximum value on X axis
  40528. * @param zmax defines the maximum value on Z axis
  40529. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40530. * @param precision defines the precision to use when computing the tiles
  40531. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40532. * @param mesh defines the hosting mesh (can be null)
  40533. */
  40534. function TiledGroundGeometry(id, scene,
  40535. /**
  40536. * Defines the minimum value on X axis
  40537. */
  40538. xmin,
  40539. /**
  40540. * Defines the minimum value on Z axis
  40541. */
  40542. zmin,
  40543. /**
  40544. * Defines the maximum value on X axis
  40545. */
  40546. xmax,
  40547. /**
  40548. * Defines the maximum value on Z axis
  40549. */
  40550. zmax,
  40551. /**
  40552. * Defines the subdivisions to apply to the ground
  40553. */
  40554. subdivisions,
  40555. /**
  40556. * Defines the precision to use when computing the tiles
  40557. */
  40558. precision, canBeRegenerated, mesh) {
  40559. if (mesh === void 0) { mesh = null; }
  40560. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40561. _this.xmin = xmin;
  40562. _this.zmin = zmin;
  40563. _this.xmax = xmax;
  40564. _this.zmax = zmax;
  40565. _this.subdivisions = subdivisions;
  40566. _this.precision = precision;
  40567. return _this;
  40568. }
  40569. /** @hidden */
  40570. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40571. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40572. };
  40573. TiledGroundGeometry.prototype.copy = function (id) {
  40574. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40575. };
  40576. return TiledGroundGeometry;
  40577. }(_PrimitiveGeometry));
  40578. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40579. /**
  40580. * Creates a plane geometry
  40581. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40582. */
  40583. var PlaneGeometry = /** @class */ (function (_super) {
  40584. __extends(PlaneGeometry, _super);
  40585. /**
  40586. * Creates a plane geometry
  40587. * @param id defines the unique ID of the geometry
  40588. * @param scene defines the hosting scene
  40589. * @param size defines the size of the plane (width === height)
  40590. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40591. * @param mesh defines the hosting mesh (can be null)
  40592. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40593. */
  40594. function PlaneGeometry(id, scene,
  40595. /**
  40596. * Defines the size of the plane (width === height)
  40597. */
  40598. size, canBeRegenerated, mesh,
  40599. /**
  40600. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40601. */
  40602. side) {
  40603. if (mesh === void 0) { mesh = null; }
  40604. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40605. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40606. _this.size = size;
  40607. _this.side = side;
  40608. return _this;
  40609. }
  40610. /** @hidden */
  40611. PlaneGeometry.prototype._regenerateVertexData = function () {
  40612. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40613. };
  40614. PlaneGeometry.prototype.copy = function (id) {
  40615. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40616. };
  40617. PlaneGeometry.prototype.serialize = function () {
  40618. var serializationObject = _super.prototype.serialize.call(this);
  40619. serializationObject.size = this.size;
  40620. return serializationObject;
  40621. };
  40622. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40623. if (scene.getGeometryByID(parsedPlane.id)) {
  40624. return null; // null since geometry could be something else than a ground...
  40625. }
  40626. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40627. if (BABYLON.Tags) {
  40628. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40629. }
  40630. scene.pushGeometry(plane, true);
  40631. return plane;
  40632. };
  40633. return PlaneGeometry;
  40634. }(_PrimitiveGeometry));
  40635. BABYLON.PlaneGeometry = PlaneGeometry;
  40636. /**
  40637. * Creates a torus knot geometry
  40638. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40639. */
  40640. var TorusKnotGeometry = /** @class */ (function (_super) {
  40641. __extends(TorusKnotGeometry, _super);
  40642. /**
  40643. * Creates a torus knot geometry
  40644. * @param id defines the unique ID of the geometry
  40645. * @param scene defines the hosting scene
  40646. * @param radius defines the radius of the torus knot
  40647. * @param tube defines the thickness of the torus knot tube
  40648. * @param radialSegments defines the number of radial segments
  40649. * @param tubularSegments defines the number of tubular segments
  40650. * @param p defines the first number of windings
  40651. * @param q defines the second number of windings
  40652. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40653. * @param mesh defines the hosting mesh (can be null)
  40654. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40655. */
  40656. function TorusKnotGeometry(id, scene,
  40657. /**
  40658. * Defines the radius of the torus knot
  40659. */
  40660. radius,
  40661. /**
  40662. * Defines the thickness of the torus knot tube
  40663. */
  40664. tube,
  40665. /**
  40666. * Defines the number of radial segments
  40667. */
  40668. radialSegments,
  40669. /**
  40670. * Defines the number of tubular segments
  40671. */
  40672. tubularSegments,
  40673. /**
  40674. * Defines the first number of windings
  40675. */
  40676. p,
  40677. /**
  40678. * Defines the second number of windings
  40679. */
  40680. q, canBeRegenerated, mesh,
  40681. /**
  40682. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40683. */
  40684. side) {
  40685. if (mesh === void 0) { mesh = null; }
  40686. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40687. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40688. _this.radius = radius;
  40689. _this.tube = tube;
  40690. _this.radialSegments = radialSegments;
  40691. _this.tubularSegments = tubularSegments;
  40692. _this.p = p;
  40693. _this.q = q;
  40694. _this.side = side;
  40695. return _this;
  40696. }
  40697. /** @hidden */
  40698. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40699. 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 });
  40700. };
  40701. TorusKnotGeometry.prototype.copy = function (id) {
  40702. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40703. };
  40704. TorusKnotGeometry.prototype.serialize = function () {
  40705. var serializationObject = _super.prototype.serialize.call(this);
  40706. serializationObject.radius = this.radius;
  40707. serializationObject.tube = this.tube;
  40708. serializationObject.radialSegments = this.radialSegments;
  40709. serializationObject.tubularSegments = this.tubularSegments;
  40710. serializationObject.p = this.p;
  40711. serializationObject.q = this.q;
  40712. return serializationObject;
  40713. };
  40714. ;
  40715. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40716. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40717. return null; // null since geometry could be something else than a ground...
  40718. }
  40719. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40720. if (BABYLON.Tags) {
  40721. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40722. }
  40723. scene.pushGeometry(torusKnot, true);
  40724. return torusKnot;
  40725. };
  40726. return TorusKnotGeometry;
  40727. }(_PrimitiveGeometry));
  40728. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40729. //}
  40730. })(BABYLON || (BABYLON = {}));
  40731. //# sourceMappingURL=babylon.geometry.js.map
  40732. var BABYLON;
  40733. (function (BABYLON) {
  40734. /**
  40735. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40736. */
  40737. var PerformanceMonitor = /** @class */ (function () {
  40738. /**
  40739. * constructor
  40740. * @param frameSampleSize The number of samples required to saturate the sliding window
  40741. */
  40742. function PerformanceMonitor(frameSampleSize) {
  40743. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40744. this._enabled = true;
  40745. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40746. }
  40747. /**
  40748. * Samples current frame
  40749. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40750. */
  40751. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40752. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40753. if (!this._enabled)
  40754. return;
  40755. if (this._lastFrameTimeMs != null) {
  40756. var dt = timeMs - this._lastFrameTimeMs;
  40757. this._rollingFrameTime.add(dt);
  40758. }
  40759. this._lastFrameTimeMs = timeMs;
  40760. };
  40761. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40762. /**
  40763. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40764. * @return Average frame time in milliseconds
  40765. */
  40766. get: function () {
  40767. return this._rollingFrameTime.average;
  40768. },
  40769. enumerable: true,
  40770. configurable: true
  40771. });
  40772. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40773. /**
  40774. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40775. * @return Frame time variance in milliseconds squared
  40776. */
  40777. get: function () {
  40778. return this._rollingFrameTime.variance;
  40779. },
  40780. enumerable: true,
  40781. configurable: true
  40782. });
  40783. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40784. /**
  40785. * Returns the frame time of the most recent frame
  40786. * @return Frame time in milliseconds
  40787. */
  40788. get: function () {
  40789. return this._rollingFrameTime.history(0);
  40790. },
  40791. enumerable: true,
  40792. configurable: true
  40793. });
  40794. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40795. /**
  40796. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40797. * @return Framerate in frames per second
  40798. */
  40799. get: function () {
  40800. return 1000.0 / this._rollingFrameTime.average;
  40801. },
  40802. enumerable: true,
  40803. configurable: true
  40804. });
  40805. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40806. /**
  40807. * Returns the average framerate in frames per second using the most recent frame time
  40808. * @return Framerate in frames per second
  40809. */
  40810. get: function () {
  40811. var history = this._rollingFrameTime.history(0);
  40812. if (history === 0) {
  40813. return 0;
  40814. }
  40815. return 1000.0 / history;
  40816. },
  40817. enumerable: true,
  40818. configurable: true
  40819. });
  40820. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40821. /**
  40822. * Returns true if enough samples have been taken to completely fill the sliding window
  40823. * @return true if saturated
  40824. */
  40825. get: function () {
  40826. return this._rollingFrameTime.isSaturated();
  40827. },
  40828. enumerable: true,
  40829. configurable: true
  40830. });
  40831. /**
  40832. * Enables contributions to the sliding window sample set
  40833. */
  40834. PerformanceMonitor.prototype.enable = function () {
  40835. this._enabled = true;
  40836. };
  40837. /**
  40838. * Disables contributions to the sliding window sample set
  40839. * Samples will not be interpolated over the disabled period
  40840. */
  40841. PerformanceMonitor.prototype.disable = function () {
  40842. this._enabled = false;
  40843. //clear last sample to avoid interpolating over the disabled period when next enabled
  40844. this._lastFrameTimeMs = null;
  40845. };
  40846. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40847. /**
  40848. * Returns true if sampling is enabled
  40849. * @return true if enabled
  40850. */
  40851. get: function () {
  40852. return this._enabled;
  40853. },
  40854. enumerable: true,
  40855. configurable: true
  40856. });
  40857. /**
  40858. * Resets performance monitor
  40859. */
  40860. PerformanceMonitor.prototype.reset = function () {
  40861. //clear last sample to avoid interpolating over the disabled period when next enabled
  40862. this._lastFrameTimeMs = null;
  40863. //wipe record
  40864. this._rollingFrameTime.reset();
  40865. };
  40866. return PerformanceMonitor;
  40867. }());
  40868. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40869. /**
  40870. * RollingAverage
  40871. *
  40872. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40873. */
  40874. var RollingAverage = /** @class */ (function () {
  40875. /**
  40876. * constructor
  40877. * @param length The number of samples required to saturate the sliding window
  40878. */
  40879. function RollingAverage(length) {
  40880. this._samples = new Array(length);
  40881. this.reset();
  40882. }
  40883. /**
  40884. * Adds a sample to the sample set
  40885. * @param v The sample value
  40886. */
  40887. RollingAverage.prototype.add = function (v) {
  40888. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40889. var delta;
  40890. //we need to check if we've already wrapped round
  40891. if (this.isSaturated()) {
  40892. //remove bottom of stack from mean
  40893. var bottomValue = this._samples[this._pos];
  40894. delta = bottomValue - this.average;
  40895. this.average -= delta / (this._sampleCount - 1);
  40896. this._m2 -= delta * (bottomValue - this.average);
  40897. }
  40898. else {
  40899. this._sampleCount++;
  40900. }
  40901. //add new value to mean
  40902. delta = v - this.average;
  40903. this.average += delta / (this._sampleCount);
  40904. this._m2 += delta * (v - this.average);
  40905. //set the new variance
  40906. this.variance = this._m2 / (this._sampleCount - 1);
  40907. this._samples[this._pos] = v;
  40908. this._pos++;
  40909. this._pos %= this._samples.length; //positive wrap around
  40910. };
  40911. /**
  40912. * Returns previously added values or null if outside of history or outside the sliding window domain
  40913. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40914. * @return Value previously recorded with add() or null if outside of range
  40915. */
  40916. RollingAverage.prototype.history = function (i) {
  40917. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40918. return 0;
  40919. }
  40920. var i0 = this._wrapPosition(this._pos - 1.0);
  40921. return this._samples[this._wrapPosition(i0 - i)];
  40922. };
  40923. /**
  40924. * Returns true if enough samples have been taken to completely fill the sliding window
  40925. * @return true if sample-set saturated
  40926. */
  40927. RollingAverage.prototype.isSaturated = function () {
  40928. return this._sampleCount >= this._samples.length;
  40929. };
  40930. /**
  40931. * Resets the rolling average (equivalent to 0 samples taken so far)
  40932. */
  40933. RollingAverage.prototype.reset = function () {
  40934. this.average = 0;
  40935. this.variance = 0;
  40936. this._sampleCount = 0;
  40937. this._pos = 0;
  40938. this._m2 = 0;
  40939. };
  40940. /**
  40941. * Wraps a value around the sample range boundaries
  40942. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40943. * @return Wrapped position in sample range
  40944. */
  40945. RollingAverage.prototype._wrapPosition = function (i) {
  40946. var max = this._samples.length;
  40947. return ((i % max) + max) % max;
  40948. };
  40949. return RollingAverage;
  40950. }());
  40951. BABYLON.RollingAverage = RollingAverage;
  40952. })(BABYLON || (BABYLON = {}));
  40953. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40954. var BABYLON;
  40955. (function (BABYLON) {
  40956. /**
  40957. * "Static Class" containing the most commonly used helper while dealing with material for
  40958. * rendering purpose.
  40959. *
  40960. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40961. *
  40962. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40963. */
  40964. var MaterialHelper = /** @class */ (function () {
  40965. function MaterialHelper() {
  40966. }
  40967. /**
  40968. * Bind the current view position to an effect.
  40969. * @param effect The effect to be bound
  40970. * @param scene The scene the eyes position is used from
  40971. */
  40972. MaterialHelper.BindEyePosition = function (effect, scene) {
  40973. if (scene._forcedViewPosition) {
  40974. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40975. return;
  40976. }
  40977. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40978. };
  40979. /**
  40980. * Helps preparing the defines values about the UVs in used in the effect.
  40981. * UVs are shared as much as we can accross chanels in the shaders.
  40982. * @param texture The texture we are preparing the UVs for
  40983. * @param defines The defines to update
  40984. * @param key The chanel key "diffuse", "specular"... used in the shader
  40985. */
  40986. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40987. defines._needUVs = true;
  40988. defines[key] = true;
  40989. if (texture.getTextureMatrix().isIdentity(true)) {
  40990. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40991. if (texture.coordinatesIndex === 0) {
  40992. defines["MAINUV1"] = true;
  40993. }
  40994. else {
  40995. defines["MAINUV2"] = true;
  40996. }
  40997. }
  40998. else {
  40999. defines[key + "DIRECTUV"] = 0;
  41000. }
  41001. };
  41002. /**
  41003. * Binds a texture matrix value to its corrsponding uniform
  41004. * @param texture The texture to bind the matrix for
  41005. * @param uniformBuffer The uniform buffer receivin the data
  41006. * @param key The chanel key "diffuse", "specular"... used in the shader
  41007. */
  41008. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41009. var matrix = texture.getTextureMatrix();
  41010. if (!matrix.isIdentity(true)) {
  41011. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41012. }
  41013. };
  41014. /**
  41015. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41016. * @param mesh defines the current mesh
  41017. * @param scene defines the current scene
  41018. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41019. * @param pointsCloud defines if point cloud rendering has to be turned on
  41020. * @param fogEnabled defines if fog has to be turned on
  41021. * @param alphaTest defines if alpha testing has to be turned on
  41022. * @param defines defines the current list of defines
  41023. */
  41024. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41025. if (defines._areMiscDirty) {
  41026. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41027. defines["POINTSIZE"] = pointsCloud;
  41028. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41029. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41030. defines["ALPHATEST"] = alphaTest;
  41031. }
  41032. };
  41033. /**
  41034. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41035. * @param scene defines the current scene
  41036. * @param engine defines the current engine
  41037. * @param defines specifies the list of active defines
  41038. * @param useInstances defines if instances have to be turned on
  41039. * @param useClipPlane defines if clip plane have to be turned on
  41040. */
  41041. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41042. if (useClipPlane === void 0) { useClipPlane = null; }
  41043. var changed = false;
  41044. var useClipPlane1 = false;
  41045. var useClipPlane2 = false;
  41046. var useClipPlane3 = false;
  41047. var useClipPlane4 = false;
  41048. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41049. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41050. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41051. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41052. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41053. defines["CLIPPLANE"] = useClipPlane1;
  41054. changed = true;
  41055. }
  41056. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41057. defines["CLIPPLANE2"] = useClipPlane2;
  41058. changed = true;
  41059. }
  41060. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41061. defines["CLIPPLANE3"] = useClipPlane3;
  41062. changed = true;
  41063. }
  41064. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41065. defines["CLIPPLANE4"] = useClipPlane4;
  41066. changed = true;
  41067. }
  41068. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41069. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41070. changed = true;
  41071. }
  41072. if (defines["INSTANCES"] !== useInstances) {
  41073. defines["INSTANCES"] = useInstances;
  41074. changed = true;
  41075. }
  41076. if (changed) {
  41077. defines.markAsUnprocessed();
  41078. }
  41079. };
  41080. /**
  41081. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41082. * @param mesh The mesh containing the geometry data we will draw
  41083. * @param defines The defines to update
  41084. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41085. * @param useBones Precise whether bones should be used or not (override mesh info)
  41086. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41087. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41088. * @returns false if defines are considered not dirty and have not been checked
  41089. */
  41090. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41091. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41092. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41093. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41094. return false;
  41095. }
  41096. defines._normals = defines._needNormals;
  41097. defines._uvs = defines._needUVs;
  41098. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41099. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41100. defines["TANGENT"] = true;
  41101. }
  41102. if (defines._needUVs) {
  41103. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41104. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41105. }
  41106. else {
  41107. defines["UV1"] = false;
  41108. defines["UV2"] = false;
  41109. }
  41110. if (useVertexColor) {
  41111. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41112. defines["VERTEXCOLOR"] = hasVertexColors;
  41113. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41114. }
  41115. if (useBones) {
  41116. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41117. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41118. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41119. }
  41120. else {
  41121. defines["NUM_BONE_INFLUENCERS"] = 0;
  41122. defines["BonesPerMesh"] = 0;
  41123. }
  41124. }
  41125. if (useMorphTargets) {
  41126. var manager = mesh.morphTargetManager;
  41127. if (manager) {
  41128. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41129. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41130. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41131. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41132. }
  41133. else {
  41134. defines["MORPHTARGETS_TANGENT"] = false;
  41135. defines["MORPHTARGETS_NORMAL"] = false;
  41136. defines["MORPHTARGETS"] = false;
  41137. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41138. }
  41139. }
  41140. return true;
  41141. };
  41142. /**
  41143. * Prepares the defines related to the light information passed in parameter
  41144. * @param scene The scene we are intending to draw
  41145. * @param mesh The mesh the effect is compiling for
  41146. * @param defines The defines to update
  41147. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41148. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41149. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41150. * @returns true if normals will be required for the rest of the effect
  41151. */
  41152. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41153. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41154. if (disableLighting === void 0) { disableLighting = false; }
  41155. if (!defines._areLightsDirty) {
  41156. return defines._needNormals;
  41157. }
  41158. var lightIndex = 0;
  41159. var needNormals = false;
  41160. var needRebuild = false;
  41161. var lightmapMode = false;
  41162. var shadowEnabled = false;
  41163. var specularEnabled = false;
  41164. if (scene.lightsEnabled && !disableLighting) {
  41165. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41166. var light = _a[_i];
  41167. needNormals = true;
  41168. if (defines["LIGHT" + lightIndex] === undefined) {
  41169. needRebuild = true;
  41170. }
  41171. defines["LIGHT" + lightIndex] = true;
  41172. defines["SPOTLIGHT" + lightIndex] = false;
  41173. defines["HEMILIGHT" + lightIndex] = false;
  41174. defines["POINTLIGHT" + lightIndex] = false;
  41175. defines["DIRLIGHT" + lightIndex] = false;
  41176. light.prepareLightSpecificDefines(defines, lightIndex);
  41177. // FallOff.
  41178. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41179. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41180. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41181. switch (light.falloffType) {
  41182. case BABYLON.Light.FALLOFF_GLTF:
  41183. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41184. break;
  41185. case BABYLON.Light.FALLOFF_PHYSICAL:
  41186. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41187. break;
  41188. case BABYLON.Light.FALLOFF_STANDARD:
  41189. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41190. break;
  41191. }
  41192. // Specular
  41193. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41194. specularEnabled = true;
  41195. }
  41196. // Shadows
  41197. defines["SHADOW" + lightIndex] = false;
  41198. defines["SHADOWPCF" + lightIndex] = false;
  41199. defines["SHADOWPCSS" + lightIndex] = false;
  41200. defines["SHADOWPOISSON" + lightIndex] = false;
  41201. defines["SHADOWESM" + lightIndex] = false;
  41202. defines["SHADOWCUBE" + lightIndex] = false;
  41203. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41204. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41205. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41206. var shadowGenerator = light.getShadowGenerator();
  41207. if (shadowGenerator) {
  41208. var shadowMap = shadowGenerator.getShadowMap();
  41209. if (shadowMap) {
  41210. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41211. shadowEnabled = true;
  41212. shadowGenerator.prepareDefines(defines, lightIndex);
  41213. }
  41214. }
  41215. }
  41216. }
  41217. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41218. lightmapMode = true;
  41219. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41220. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41221. }
  41222. else {
  41223. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41224. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41225. }
  41226. lightIndex++;
  41227. if (lightIndex === maxSimultaneousLights)
  41228. break;
  41229. }
  41230. }
  41231. defines["SPECULARTERM"] = specularEnabled;
  41232. defines["SHADOWS"] = shadowEnabled;
  41233. // Resetting all other lights if any
  41234. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41235. if (defines["LIGHT" + index] !== undefined) {
  41236. defines["LIGHT" + index] = false;
  41237. defines["HEMILIGHT" + lightIndex] = false;
  41238. defines["POINTLIGHT" + lightIndex] = false;
  41239. defines["DIRLIGHT" + lightIndex] = false;
  41240. defines["SPOTLIGHT" + lightIndex] = false;
  41241. defines["SHADOW" + lightIndex] = false;
  41242. }
  41243. }
  41244. var caps = scene.getEngine().getCaps();
  41245. if (defines["SHADOWFLOAT"] === undefined) {
  41246. needRebuild = true;
  41247. }
  41248. defines["SHADOWFLOAT"] = shadowEnabled &&
  41249. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41250. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41251. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41252. if (needRebuild) {
  41253. defines.rebuild();
  41254. }
  41255. return needNormals;
  41256. };
  41257. /**
  41258. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41259. * that won t be acctive due to defines being turned off.
  41260. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41261. * @param samplersList The samplers list
  41262. * @param defines The defines helping in the list generation
  41263. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41264. */
  41265. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41266. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41267. var uniformsList;
  41268. var uniformBuffersList = null;
  41269. if (uniformsListOrOptions.uniformsNames) {
  41270. var options = uniformsListOrOptions;
  41271. uniformsList = options.uniformsNames;
  41272. uniformBuffersList = options.uniformBuffersNames;
  41273. samplersList = options.samplers;
  41274. defines = options.defines;
  41275. maxSimultaneousLights = options.maxSimultaneousLights;
  41276. }
  41277. else {
  41278. uniformsList = uniformsListOrOptions;
  41279. if (!samplersList) {
  41280. samplersList = [];
  41281. }
  41282. }
  41283. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41284. if (!defines["LIGHT" + lightIndex]) {
  41285. break;
  41286. }
  41287. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41288. if (uniformBuffersList) {
  41289. uniformBuffersList.push("Light" + lightIndex);
  41290. }
  41291. samplersList.push("shadowSampler" + lightIndex);
  41292. samplersList.push("depthSampler" + lightIndex);
  41293. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41294. samplersList.push("projectionLightSampler" + lightIndex);
  41295. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41296. }
  41297. }
  41298. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41299. uniformsList.push("morphTargetInfluences");
  41300. }
  41301. };
  41302. /**
  41303. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41304. * @param defines The defines to update while falling back
  41305. * @param fallbacks The authorized effect fallbacks
  41306. * @param maxSimultaneousLights The maximum number of lights allowed
  41307. * @param rank the current rank of the Effect
  41308. * @returns The newly affected rank
  41309. */
  41310. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41311. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41312. if (rank === void 0) { rank = 0; }
  41313. var lightFallbackRank = 0;
  41314. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41315. if (!defines["LIGHT" + lightIndex]) {
  41316. break;
  41317. }
  41318. if (lightIndex > 0) {
  41319. lightFallbackRank = rank + lightIndex;
  41320. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41321. }
  41322. if (!defines["SHADOWS"]) {
  41323. if (defines["SHADOW" + lightIndex]) {
  41324. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41325. }
  41326. if (defines["SHADOWPCF" + lightIndex]) {
  41327. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41328. }
  41329. if (defines["SHADOWPCSS" + lightIndex]) {
  41330. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41331. }
  41332. if (defines["SHADOWPOISSON" + lightIndex]) {
  41333. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41334. }
  41335. if (defines["SHADOWESM" + lightIndex]) {
  41336. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41337. }
  41338. }
  41339. }
  41340. return lightFallbackRank++;
  41341. };
  41342. /**
  41343. * Prepares the list of attributes required for morph targets according to the effect defines.
  41344. * @param attribs The current list of supported attribs
  41345. * @param mesh The mesh to prepare the morph targets attributes for
  41346. * @param defines The current Defines of the effect
  41347. */
  41348. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41349. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41350. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41351. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41352. var manager = mesh.morphTargetManager;
  41353. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41354. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41355. for (var index = 0; index < influencers; index++) {
  41356. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41357. if (normal) {
  41358. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41359. }
  41360. if (tangent) {
  41361. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41362. }
  41363. if (attribs.length > maxAttributesCount) {
  41364. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41365. }
  41366. }
  41367. }
  41368. };
  41369. /**
  41370. * Prepares the list of attributes required for bones according to the effect defines.
  41371. * @param attribs The current list of supported attribs
  41372. * @param mesh The mesh to prepare the bones attributes for
  41373. * @param defines The current Defines of the effect
  41374. * @param fallbacks The current efffect fallback strategy
  41375. */
  41376. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41377. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41378. fallbacks.addCPUSkinningFallback(0, mesh);
  41379. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41380. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41381. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41382. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41383. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41384. }
  41385. }
  41386. };
  41387. /**
  41388. * Prepares the list of attributes required for instances according to the effect defines.
  41389. * @param attribs The current list of supported attribs
  41390. * @param defines The current Defines of the effect
  41391. */
  41392. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41393. if (defines["INSTANCES"]) {
  41394. attribs.push("world0");
  41395. attribs.push("world1");
  41396. attribs.push("world2");
  41397. attribs.push("world3");
  41398. }
  41399. };
  41400. /**
  41401. * Binds the light shadow information to the effect for the given mesh.
  41402. * @param light The light containing the generator
  41403. * @param scene The scene the lights belongs to
  41404. * @param mesh The mesh we are binding the information to render
  41405. * @param lightIndex The light index in the effect used to render the mesh
  41406. * @param effect The effect we are binding the data to
  41407. */
  41408. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41409. if (light.shadowEnabled && mesh.receiveShadows) {
  41410. var shadowGenerator = light.getShadowGenerator();
  41411. if (shadowGenerator) {
  41412. shadowGenerator.bindShadowLight(lightIndex, effect);
  41413. }
  41414. }
  41415. };
  41416. /**
  41417. * Binds the light information to the effect.
  41418. * @param light The light containing the generator
  41419. * @param effect The effect we are binding the data to
  41420. * @param lightIndex The light index in the effect used to render
  41421. */
  41422. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41423. light.transferToEffect(effect, lightIndex + "");
  41424. };
  41425. /**
  41426. * Binds the lights information from the scene to the effect for the given mesh.
  41427. * @param scene The scene the lights belongs to
  41428. * @param mesh The mesh we are binding the information to render
  41429. * @param effect The effect we are binding the data to
  41430. * @param defines The generated defines for the effect
  41431. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41432. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41433. */
  41434. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41435. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41436. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41437. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41438. for (var i = 0; i < len; i++) {
  41439. var light = mesh._lightSources[i];
  41440. var iAsString = i.toString();
  41441. var scaledIntensity = light.getScaledIntensity();
  41442. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41443. MaterialHelper.BindLightProperties(light, effect, i);
  41444. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41445. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41446. if (defines["SPECULARTERM"]) {
  41447. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41448. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41449. }
  41450. // Shadows
  41451. if (scene.shadowsEnabled) {
  41452. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41453. }
  41454. light._uniformBuffer.update();
  41455. }
  41456. };
  41457. /**
  41458. * Binds the fog information from the scene to the effect for the given mesh.
  41459. * @param scene The scene the lights belongs to
  41460. * @param mesh The mesh we are binding the information to render
  41461. * @param effect The effect we are binding the data to
  41462. * @param linearSpace Defines if the fog effect is applied in linear space
  41463. */
  41464. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  41465. if (linearSpace === void 0) { linearSpace = false; }
  41466. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41467. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41468. // Convert fog color to linear space if used in a linear space computed shader.
  41469. if (linearSpace) {
  41470. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  41471. effect.setColor3("vFogColor", this._tempFogColor);
  41472. }
  41473. else {
  41474. effect.setColor3("vFogColor", scene.fogColor);
  41475. }
  41476. }
  41477. };
  41478. /**
  41479. * Binds the bones information from the mesh to the effect.
  41480. * @param mesh The mesh we are binding the information to render
  41481. * @param effect The effect we are binding the data to
  41482. */
  41483. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41484. if (!effect || !mesh) {
  41485. return;
  41486. }
  41487. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41488. mesh.computeBonesUsingShaders = false;
  41489. }
  41490. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41491. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41492. if (matrices) {
  41493. effect.setMatrices("mBones", matrices);
  41494. }
  41495. }
  41496. };
  41497. /**
  41498. * Binds the morph targets information from the mesh to the effect.
  41499. * @param abstractMesh The mesh we are binding the information to render
  41500. * @param effect The effect we are binding the data to
  41501. */
  41502. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41503. var manager = abstractMesh.morphTargetManager;
  41504. if (!abstractMesh || !manager) {
  41505. return;
  41506. }
  41507. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41508. };
  41509. /**
  41510. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41511. * @param defines The generated defines used in the effect
  41512. * @param effect The effect we are binding the data to
  41513. * @param scene The scene we are willing to render with logarithmic scale for
  41514. */
  41515. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41516. if (defines["LOGARITHMICDEPTH"]) {
  41517. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41518. }
  41519. };
  41520. /**
  41521. * Binds the clip plane information from the scene to the effect.
  41522. * @param scene The scene the clip plane information are extracted from
  41523. * @param effect The effect we are binding the data to
  41524. */
  41525. MaterialHelper.BindClipPlane = function (effect, scene) {
  41526. if (scene.clipPlane) {
  41527. var clipPlane = scene.clipPlane;
  41528. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41529. }
  41530. if (scene.clipPlane2) {
  41531. var clipPlane = scene.clipPlane2;
  41532. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41533. }
  41534. if (scene.clipPlane3) {
  41535. var clipPlane = scene.clipPlane3;
  41536. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41537. }
  41538. if (scene.clipPlane4) {
  41539. var clipPlane = scene.clipPlane4;
  41540. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41541. }
  41542. };
  41543. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  41544. return MaterialHelper;
  41545. }());
  41546. BABYLON.MaterialHelper = MaterialHelper;
  41547. })(BABYLON || (BABYLON = {}));
  41548. //# sourceMappingURL=babylon.materialHelper.js.map
  41549. var BABYLON;
  41550. (function (BABYLON) {
  41551. var PushMaterial = /** @class */ (function (_super) {
  41552. __extends(PushMaterial, _super);
  41553. function PushMaterial(name, scene) {
  41554. var _this = _super.call(this, name, scene) || this;
  41555. _this._normalMatrix = new BABYLON.Matrix();
  41556. _this.storeEffectOnSubMeshes = true;
  41557. return _this;
  41558. }
  41559. PushMaterial.prototype.getEffect = function () {
  41560. return this._activeEffect;
  41561. };
  41562. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41563. if (!mesh) {
  41564. return false;
  41565. }
  41566. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41567. return true;
  41568. }
  41569. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41570. };
  41571. /**
  41572. * Binds the given world matrix to the active effect
  41573. *
  41574. * @param world the matrix to bind
  41575. */
  41576. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41577. this._activeEffect.setMatrix("world", world);
  41578. };
  41579. /**
  41580. * Binds the given normal matrix to the active effect
  41581. *
  41582. * @param normalMatrix the matrix to bind
  41583. */
  41584. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41585. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41586. };
  41587. PushMaterial.prototype.bind = function (world, mesh) {
  41588. if (!mesh) {
  41589. return;
  41590. }
  41591. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41592. };
  41593. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41594. if (effect === void 0) { effect = null; }
  41595. _super.prototype._afterBind.call(this, mesh);
  41596. this.getScene()._cachedEffect = effect;
  41597. };
  41598. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41599. if (visibility === void 0) { visibility = 1; }
  41600. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41601. };
  41602. return PushMaterial;
  41603. }(BABYLON.Material));
  41604. BABYLON.PushMaterial = PushMaterial;
  41605. })(BABYLON || (BABYLON = {}));
  41606. //# sourceMappingURL=babylon.pushMaterial.js.map
  41607. var BABYLON;
  41608. (function (BABYLON) {
  41609. /** @hidden */
  41610. var StandardMaterialDefines = /** @class */ (function (_super) {
  41611. __extends(StandardMaterialDefines, _super);
  41612. function StandardMaterialDefines() {
  41613. var _this = _super.call(this) || this;
  41614. _this.MAINUV1 = false;
  41615. _this.MAINUV2 = false;
  41616. _this.DIFFUSE = false;
  41617. _this.DIFFUSEDIRECTUV = 0;
  41618. _this.AMBIENT = false;
  41619. _this.AMBIENTDIRECTUV = 0;
  41620. _this.OPACITY = false;
  41621. _this.OPACITYDIRECTUV = 0;
  41622. _this.OPACITYRGB = false;
  41623. _this.REFLECTION = false;
  41624. _this.EMISSIVE = false;
  41625. _this.EMISSIVEDIRECTUV = 0;
  41626. _this.SPECULAR = false;
  41627. _this.SPECULARDIRECTUV = 0;
  41628. _this.BUMP = false;
  41629. _this.BUMPDIRECTUV = 0;
  41630. _this.PARALLAX = false;
  41631. _this.PARALLAXOCCLUSION = false;
  41632. _this.SPECULAROVERALPHA = false;
  41633. _this.CLIPPLANE = false;
  41634. _this.CLIPPLANE2 = false;
  41635. _this.CLIPPLANE3 = false;
  41636. _this.CLIPPLANE4 = false;
  41637. _this.ALPHATEST = false;
  41638. _this.DEPTHPREPASS = false;
  41639. _this.ALPHAFROMDIFFUSE = false;
  41640. _this.POINTSIZE = false;
  41641. _this.FOG = false;
  41642. _this.SPECULARTERM = false;
  41643. _this.DIFFUSEFRESNEL = false;
  41644. _this.OPACITYFRESNEL = false;
  41645. _this.REFLECTIONFRESNEL = false;
  41646. _this.REFRACTIONFRESNEL = false;
  41647. _this.EMISSIVEFRESNEL = false;
  41648. _this.FRESNEL = false;
  41649. _this.NORMAL = false;
  41650. _this.UV1 = false;
  41651. _this.UV2 = false;
  41652. _this.VERTEXCOLOR = false;
  41653. _this.VERTEXALPHA = false;
  41654. _this.NUM_BONE_INFLUENCERS = 0;
  41655. _this.BonesPerMesh = 0;
  41656. _this.INSTANCES = false;
  41657. _this.GLOSSINESS = false;
  41658. _this.ROUGHNESS = false;
  41659. _this.EMISSIVEASILLUMINATION = false;
  41660. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41661. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41662. _this.LIGHTMAP = false;
  41663. _this.LIGHTMAPDIRECTUV = 0;
  41664. _this.OBJECTSPACE_NORMALMAP = false;
  41665. _this.USELIGHTMAPASSHADOWMAP = false;
  41666. _this.REFLECTIONMAP_3D = false;
  41667. _this.REFLECTIONMAP_SPHERICAL = false;
  41668. _this.REFLECTIONMAP_PLANAR = false;
  41669. _this.REFLECTIONMAP_CUBIC = false;
  41670. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41671. _this.REFLECTIONMAP_PROJECTION = false;
  41672. _this.REFLECTIONMAP_SKYBOX = false;
  41673. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41674. _this.REFLECTIONMAP_EXPLICIT = false;
  41675. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41676. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41677. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41678. _this.INVERTCUBICMAP = false;
  41679. _this.LOGARITHMICDEPTH = false;
  41680. _this.REFRACTION = false;
  41681. _this.REFRACTIONMAP_3D = false;
  41682. _this.REFLECTIONOVERALPHA = false;
  41683. _this.TWOSIDEDLIGHTING = false;
  41684. _this.SHADOWFLOAT = false;
  41685. _this.MORPHTARGETS = false;
  41686. _this.MORPHTARGETS_NORMAL = false;
  41687. _this.MORPHTARGETS_TANGENT = false;
  41688. _this.NUM_MORPH_INFLUENCERS = 0;
  41689. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41690. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41691. _this.IMAGEPROCESSING = false;
  41692. _this.VIGNETTE = false;
  41693. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41694. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41695. _this.TONEMAPPING = false;
  41696. _this.TONEMAPPING_ACES = false;
  41697. _this.CONTRAST = false;
  41698. _this.COLORCURVES = false;
  41699. _this.COLORGRADING = false;
  41700. _this.COLORGRADING3D = false;
  41701. _this.SAMPLER3DGREENDEPTH = false;
  41702. _this.SAMPLER3DBGRMAP = false;
  41703. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41704. /**
  41705. * If the reflection texture on this material is in linear color space
  41706. * @hidden
  41707. */
  41708. _this.IS_REFLECTION_LINEAR = false;
  41709. /**
  41710. * If the refraction texture on this material is in linear color space
  41711. * @hidden
  41712. */
  41713. _this.IS_REFRACTION_LINEAR = false;
  41714. _this.EXPOSURE = false;
  41715. _this.rebuild();
  41716. return _this;
  41717. }
  41718. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41719. var modes = [
  41720. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41721. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41722. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41723. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41724. ];
  41725. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41726. var mode = modes_1[_i];
  41727. this[mode] = (mode === modeToEnable);
  41728. }
  41729. };
  41730. return StandardMaterialDefines;
  41731. }(BABYLON.MaterialDefines));
  41732. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41733. var StandardMaterial = /** @class */ (function (_super) {
  41734. __extends(StandardMaterial, _super);
  41735. function StandardMaterial(name, scene) {
  41736. var _this = _super.call(this, name, scene) || this;
  41737. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41738. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41739. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41740. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41741. _this.specularPower = 64;
  41742. _this._useAlphaFromDiffuseTexture = false;
  41743. _this._useEmissiveAsIllumination = false;
  41744. _this._linkEmissiveWithDiffuse = false;
  41745. _this._useSpecularOverAlpha = false;
  41746. _this._useReflectionOverAlpha = false;
  41747. _this._disableLighting = false;
  41748. _this._useObjectSpaceNormalMap = false;
  41749. _this._useParallax = false;
  41750. _this._useParallaxOcclusion = false;
  41751. _this.parallaxScaleBias = 0.05;
  41752. _this._roughness = 0;
  41753. _this.indexOfRefraction = 0.98;
  41754. _this.invertRefractionY = true;
  41755. /**
  41756. * Defines the alpha limits in alpha test mode
  41757. */
  41758. _this.alphaCutOff = 0.4;
  41759. _this._useLightmapAsShadowmap = false;
  41760. _this._useReflectionFresnelFromSpecular = false;
  41761. _this._useGlossinessFromSpecularMapAlpha = false;
  41762. _this._maxSimultaneousLights = 4;
  41763. /**
  41764. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41765. */
  41766. _this._invertNormalMapX = false;
  41767. /**
  41768. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41769. */
  41770. _this._invertNormalMapY = false;
  41771. /**
  41772. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41773. */
  41774. _this._twoSidedLighting = false;
  41775. _this._renderTargets = new BABYLON.SmartArray(16);
  41776. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41777. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41778. // Setup the default processing configuration to the scene.
  41779. _this._attachImageProcessingConfiguration(null);
  41780. _this.getRenderTargetTextures = function () {
  41781. _this._renderTargets.reset();
  41782. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41783. _this._renderTargets.push(_this._reflectionTexture);
  41784. }
  41785. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41786. _this._renderTargets.push(_this._refractionTexture);
  41787. }
  41788. return _this._renderTargets;
  41789. };
  41790. return _this;
  41791. }
  41792. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41793. /**
  41794. * Gets the image processing configuration used either in this material.
  41795. */
  41796. get: function () {
  41797. return this._imageProcessingConfiguration;
  41798. },
  41799. /**
  41800. * Sets the Default image processing configuration used either in the this material.
  41801. *
  41802. * If sets to null, the scene one is in use.
  41803. */
  41804. set: function (value) {
  41805. this._attachImageProcessingConfiguration(value);
  41806. // Ensure the effect will be rebuilt.
  41807. this._markAllSubMeshesAsTexturesDirty();
  41808. },
  41809. enumerable: true,
  41810. configurable: true
  41811. });
  41812. /**
  41813. * Attaches a new image processing configuration to the Standard Material.
  41814. * @param configuration
  41815. */
  41816. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41817. var _this = this;
  41818. if (configuration === this._imageProcessingConfiguration) {
  41819. return;
  41820. }
  41821. // Detaches observer.
  41822. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41823. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41824. }
  41825. // Pick the scene configuration if needed.
  41826. if (!configuration) {
  41827. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41828. }
  41829. else {
  41830. this._imageProcessingConfiguration = configuration;
  41831. }
  41832. // Attaches observer.
  41833. if (this._imageProcessingConfiguration) {
  41834. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41835. _this._markAllSubMeshesAsImageProcessingDirty();
  41836. });
  41837. }
  41838. };
  41839. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41840. /**
  41841. * Gets wether the color curves effect is enabled.
  41842. */
  41843. get: function () {
  41844. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41845. },
  41846. /**
  41847. * Sets wether the color curves effect is enabled.
  41848. */
  41849. set: function (value) {
  41850. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41851. },
  41852. enumerable: true,
  41853. configurable: true
  41854. });
  41855. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41856. /**
  41857. * Gets wether the color grading effect is enabled.
  41858. */
  41859. get: function () {
  41860. return this.imageProcessingConfiguration.colorGradingEnabled;
  41861. },
  41862. /**
  41863. * Gets wether the color grading effect is enabled.
  41864. */
  41865. set: function (value) {
  41866. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41867. },
  41868. enumerable: true,
  41869. configurable: true
  41870. });
  41871. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41872. /**
  41873. * Gets wether tonemapping is enabled or not.
  41874. */
  41875. get: function () {
  41876. return this._imageProcessingConfiguration.toneMappingEnabled;
  41877. },
  41878. /**
  41879. * Sets wether tonemapping is enabled or not
  41880. */
  41881. set: function (value) {
  41882. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41883. },
  41884. enumerable: true,
  41885. configurable: true
  41886. });
  41887. ;
  41888. ;
  41889. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41890. /**
  41891. * The camera exposure used on this material.
  41892. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41893. * This corresponds to a photographic exposure.
  41894. */
  41895. get: function () {
  41896. return this._imageProcessingConfiguration.exposure;
  41897. },
  41898. /**
  41899. * The camera exposure used on this material.
  41900. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41901. * This corresponds to a photographic exposure.
  41902. */
  41903. set: function (value) {
  41904. this._imageProcessingConfiguration.exposure = value;
  41905. },
  41906. enumerable: true,
  41907. configurable: true
  41908. });
  41909. ;
  41910. ;
  41911. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41912. /**
  41913. * Gets The camera contrast used on this material.
  41914. */
  41915. get: function () {
  41916. return this._imageProcessingConfiguration.contrast;
  41917. },
  41918. /**
  41919. * Sets The camera contrast used on this material.
  41920. */
  41921. set: function (value) {
  41922. this._imageProcessingConfiguration.contrast = value;
  41923. },
  41924. enumerable: true,
  41925. configurable: true
  41926. });
  41927. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41928. /**
  41929. * Gets the Color Grading 2D Lookup Texture.
  41930. */
  41931. get: function () {
  41932. return this._imageProcessingConfiguration.colorGradingTexture;
  41933. },
  41934. /**
  41935. * Sets the Color Grading 2D Lookup Texture.
  41936. */
  41937. set: function (value) {
  41938. this._imageProcessingConfiguration.colorGradingTexture = value;
  41939. },
  41940. enumerable: true,
  41941. configurable: true
  41942. });
  41943. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41944. /**
  41945. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41946. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41947. * 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;
  41948. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41949. */
  41950. get: function () {
  41951. return this._imageProcessingConfiguration.colorCurves;
  41952. },
  41953. /**
  41954. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41955. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41956. * 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;
  41957. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41958. */
  41959. set: function (value) {
  41960. this._imageProcessingConfiguration.colorCurves = value;
  41961. },
  41962. enumerable: true,
  41963. configurable: true
  41964. });
  41965. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41966. /**
  41967. * Gets a boolean indicating that current material needs to register RTT
  41968. */
  41969. get: function () {
  41970. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41971. return true;
  41972. }
  41973. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41974. return true;
  41975. }
  41976. return false;
  41977. },
  41978. enumerable: true,
  41979. configurable: true
  41980. });
  41981. StandardMaterial.prototype.getClassName = function () {
  41982. return "StandardMaterial";
  41983. };
  41984. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41985. get: function () {
  41986. return this._useLogarithmicDepth;
  41987. },
  41988. set: function (value) {
  41989. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41990. this._markAllSubMeshesAsMiscDirty();
  41991. },
  41992. enumerable: true,
  41993. configurable: true
  41994. });
  41995. StandardMaterial.prototype.needAlphaBlending = function () {
  41996. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41997. };
  41998. StandardMaterial.prototype.needAlphaTesting = function () {
  41999. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42000. };
  42001. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42002. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42003. };
  42004. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42005. return this._diffuseTexture;
  42006. };
  42007. /**
  42008. * Child classes can use it to update shaders
  42009. */
  42010. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42011. if (useInstances === void 0) { useInstances = false; }
  42012. if (subMesh.effect && this.isFrozen) {
  42013. if (this._wasPreviouslyReady) {
  42014. return true;
  42015. }
  42016. }
  42017. if (!subMesh._materialDefines) {
  42018. subMesh._materialDefines = new StandardMaterialDefines();
  42019. }
  42020. var scene = this.getScene();
  42021. var defines = subMesh._materialDefines;
  42022. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42023. if (defines._renderId === scene.getRenderId()) {
  42024. return true;
  42025. }
  42026. }
  42027. var engine = scene.getEngine();
  42028. // Lights
  42029. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42030. // Textures
  42031. if (defines._areTexturesDirty) {
  42032. defines._needUVs = false;
  42033. defines.MAINUV1 = false;
  42034. defines.MAINUV2 = false;
  42035. if (scene.texturesEnabled) {
  42036. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42037. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42038. return false;
  42039. }
  42040. else {
  42041. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42042. }
  42043. }
  42044. else {
  42045. defines.DIFFUSE = false;
  42046. }
  42047. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42048. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42049. return false;
  42050. }
  42051. else {
  42052. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42053. }
  42054. }
  42055. else {
  42056. defines.AMBIENT = false;
  42057. }
  42058. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42059. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42060. return false;
  42061. }
  42062. else {
  42063. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42064. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42065. }
  42066. }
  42067. else {
  42068. defines.OPACITY = false;
  42069. }
  42070. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42071. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42072. return false;
  42073. }
  42074. else {
  42075. defines._needNormals = true;
  42076. defines.REFLECTION = true;
  42077. defines.ROUGHNESS = (this._roughness > 0);
  42078. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42079. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42080. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42081. switch (this._reflectionTexture.coordinatesMode) {
  42082. case BABYLON.Texture.EXPLICIT_MODE:
  42083. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42084. break;
  42085. case BABYLON.Texture.PLANAR_MODE:
  42086. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42087. break;
  42088. case BABYLON.Texture.PROJECTION_MODE:
  42089. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42090. break;
  42091. case BABYLON.Texture.SKYBOX_MODE:
  42092. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42093. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42094. break;
  42095. case BABYLON.Texture.SPHERICAL_MODE:
  42096. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42097. break;
  42098. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42099. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42100. break;
  42101. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42102. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42103. break;
  42104. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42105. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42106. break;
  42107. case BABYLON.Texture.CUBIC_MODE:
  42108. case BABYLON.Texture.INVCUBIC_MODE:
  42109. default:
  42110. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42111. break;
  42112. }
  42113. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42114. }
  42115. }
  42116. else {
  42117. defines.REFLECTION = false;
  42118. }
  42119. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42120. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42121. return false;
  42122. }
  42123. else {
  42124. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42125. }
  42126. }
  42127. else {
  42128. defines.EMISSIVE = false;
  42129. }
  42130. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42131. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42132. return false;
  42133. }
  42134. else {
  42135. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42136. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42137. }
  42138. }
  42139. else {
  42140. defines.LIGHTMAP = false;
  42141. }
  42142. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42143. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42144. return false;
  42145. }
  42146. else {
  42147. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42148. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42149. }
  42150. }
  42151. else {
  42152. defines.SPECULAR = false;
  42153. }
  42154. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42155. // Bump texure can not be not blocking.
  42156. if (!this._bumpTexture.isReady()) {
  42157. return false;
  42158. }
  42159. else {
  42160. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42161. defines.PARALLAX = this._useParallax;
  42162. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42163. }
  42164. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42165. }
  42166. else {
  42167. defines.BUMP = false;
  42168. }
  42169. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42170. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42171. return false;
  42172. }
  42173. else {
  42174. defines._needUVs = true;
  42175. defines.REFRACTION = true;
  42176. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42177. }
  42178. }
  42179. else {
  42180. defines.REFRACTION = false;
  42181. }
  42182. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42183. }
  42184. else {
  42185. defines.DIFFUSE = false;
  42186. defines.AMBIENT = false;
  42187. defines.OPACITY = false;
  42188. defines.REFLECTION = false;
  42189. defines.EMISSIVE = false;
  42190. defines.LIGHTMAP = false;
  42191. defines.BUMP = false;
  42192. defines.REFRACTION = false;
  42193. }
  42194. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42195. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42196. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42197. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42198. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42199. }
  42200. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42201. if (!this._imageProcessingConfiguration.isReady()) {
  42202. return false;
  42203. }
  42204. this._imageProcessingConfiguration.prepareDefines(defines);
  42205. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42206. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42207. }
  42208. if (defines._areFresnelDirty) {
  42209. if (StandardMaterial.FresnelEnabled) {
  42210. // Fresnel
  42211. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42212. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42213. this._reflectionFresnelParameters) {
  42214. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42215. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42216. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42217. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42218. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42219. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42220. defines._needNormals = true;
  42221. defines.FRESNEL = true;
  42222. }
  42223. }
  42224. else {
  42225. defines.FRESNEL = false;
  42226. }
  42227. }
  42228. // Misc.
  42229. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42230. // Attribs
  42231. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42232. // Values that need to be evaluated on every frame
  42233. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42234. // Get correct effect
  42235. if (defines.isDirty) {
  42236. defines.markAsProcessed();
  42237. scene.resetCachedMaterial();
  42238. // Fallbacks
  42239. var fallbacks = new BABYLON.EffectFallbacks();
  42240. if (defines.REFLECTION) {
  42241. fallbacks.addFallback(0, "REFLECTION");
  42242. }
  42243. if (defines.SPECULAR) {
  42244. fallbacks.addFallback(0, "SPECULAR");
  42245. }
  42246. if (defines.BUMP) {
  42247. fallbacks.addFallback(0, "BUMP");
  42248. }
  42249. if (defines.PARALLAX) {
  42250. fallbacks.addFallback(1, "PARALLAX");
  42251. }
  42252. if (defines.PARALLAXOCCLUSION) {
  42253. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42254. }
  42255. if (defines.SPECULAROVERALPHA) {
  42256. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42257. }
  42258. if (defines.FOG) {
  42259. fallbacks.addFallback(1, "FOG");
  42260. }
  42261. if (defines.POINTSIZE) {
  42262. fallbacks.addFallback(0, "POINTSIZE");
  42263. }
  42264. if (defines.LOGARITHMICDEPTH) {
  42265. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42266. }
  42267. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42268. if (defines.SPECULARTERM) {
  42269. fallbacks.addFallback(0, "SPECULARTERM");
  42270. }
  42271. if (defines.DIFFUSEFRESNEL) {
  42272. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42273. }
  42274. if (defines.OPACITYFRESNEL) {
  42275. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42276. }
  42277. if (defines.REFLECTIONFRESNEL) {
  42278. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42279. }
  42280. if (defines.EMISSIVEFRESNEL) {
  42281. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42282. }
  42283. if (defines.FRESNEL) {
  42284. fallbacks.addFallback(4, "FRESNEL");
  42285. }
  42286. //Attributes
  42287. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42288. if (defines.NORMAL) {
  42289. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42290. }
  42291. if (defines.UV1) {
  42292. attribs.push(BABYLON.VertexBuffer.UVKind);
  42293. }
  42294. if (defines.UV2) {
  42295. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42296. }
  42297. if (defines.VERTEXCOLOR) {
  42298. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42299. }
  42300. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42301. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42302. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42303. var shaderName = "default";
  42304. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42305. "vFogInfos", "vFogColor", "pointSize",
  42306. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42307. "mBones",
  42308. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42309. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42310. "vReflectionPosition", "vReflectionSize",
  42311. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42312. ];
  42313. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42314. var uniformBuffers = ["Material", "Scene"];
  42315. if (BABYLON.ImageProcessingConfiguration) {
  42316. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42317. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42318. }
  42319. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42320. uniformsNames: uniforms,
  42321. uniformBuffersNames: uniformBuffers,
  42322. samplers: samplers,
  42323. defines: defines,
  42324. maxSimultaneousLights: this._maxSimultaneousLights
  42325. });
  42326. if (this.customShaderNameResolve) {
  42327. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42328. }
  42329. var join = defines.toString();
  42330. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42331. attributes: attribs,
  42332. uniformsNames: uniforms,
  42333. uniformBuffersNames: uniformBuffers,
  42334. samplers: samplers,
  42335. defines: join,
  42336. fallbacks: fallbacks,
  42337. onCompiled: this.onCompiled,
  42338. onError: this.onError,
  42339. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42340. }, engine), defines);
  42341. this.buildUniformLayout();
  42342. }
  42343. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42344. return false;
  42345. }
  42346. defines._renderId = scene.getRenderId();
  42347. this._wasPreviouslyReady = true;
  42348. return true;
  42349. };
  42350. StandardMaterial.prototype.buildUniformLayout = function () {
  42351. // Order is important !
  42352. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42353. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42354. this._uniformBuffer.addUniform("opacityParts", 4);
  42355. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42356. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42357. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42358. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42359. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42360. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42361. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42362. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42363. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42364. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42365. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42366. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42367. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42368. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42369. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42370. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42371. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42372. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42373. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42374. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42375. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42376. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42377. this._uniformBuffer.addUniform("specularMatrix", 16);
  42378. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42379. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42380. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42381. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42382. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42383. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42384. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42385. this._uniformBuffer.addUniform("pointSize", 1);
  42386. this._uniformBuffer.create();
  42387. };
  42388. StandardMaterial.prototype.unbind = function () {
  42389. if (this._activeEffect) {
  42390. var needFlag = false;
  42391. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42392. this._activeEffect.setTexture("reflection2DSampler", null);
  42393. needFlag = true;
  42394. }
  42395. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42396. this._activeEffect.setTexture("refraction2DSampler", null);
  42397. needFlag = true;
  42398. }
  42399. if (needFlag) {
  42400. this._markAllSubMeshesAsTexturesDirty();
  42401. }
  42402. }
  42403. _super.prototype.unbind.call(this);
  42404. };
  42405. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42406. var scene = this.getScene();
  42407. var defines = subMesh._materialDefines;
  42408. if (!defines) {
  42409. return;
  42410. }
  42411. var effect = subMesh.effect;
  42412. if (!effect) {
  42413. return;
  42414. }
  42415. this._activeEffect = effect;
  42416. // Matrices
  42417. this.bindOnlyWorldMatrix(world);
  42418. // Normal Matrix
  42419. if (defines.OBJECTSPACE_NORMALMAP) {
  42420. world.toNormalMatrix(this._normalMatrix);
  42421. this.bindOnlyNormalMatrix(this._normalMatrix);
  42422. }
  42423. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42424. // Bones
  42425. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42426. if (mustRebind) {
  42427. this._uniformBuffer.bindToEffect(effect, "Material");
  42428. this.bindViewProjection(effect);
  42429. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42430. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42431. // Fresnel
  42432. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42433. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42434. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42435. }
  42436. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42437. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42438. }
  42439. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42440. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42441. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42442. }
  42443. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42444. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42445. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42446. }
  42447. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42448. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42449. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42450. }
  42451. }
  42452. // Textures
  42453. if (scene.texturesEnabled) {
  42454. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42455. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42456. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42457. if (this._diffuseTexture.hasAlpha) {
  42458. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42459. }
  42460. }
  42461. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42462. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42463. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42464. }
  42465. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42466. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42467. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42468. }
  42469. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42470. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42471. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42472. if (this._reflectionTexture.boundingBoxSize) {
  42473. var cubeTexture = this._reflectionTexture;
  42474. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42475. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42476. }
  42477. }
  42478. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42479. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42480. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42481. }
  42482. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42483. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42484. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42485. }
  42486. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42487. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42488. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42489. }
  42490. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42491. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42492. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42493. if (scene._mirroredCameraPosition) {
  42494. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42495. }
  42496. else {
  42497. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42498. }
  42499. }
  42500. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42501. var depth = 1.0;
  42502. if (!this._refractionTexture.isCube) {
  42503. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42504. if (this._refractionTexture.depth) {
  42505. depth = this._refractionTexture.depth;
  42506. }
  42507. }
  42508. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42509. }
  42510. }
  42511. // Point size
  42512. if (this.pointsCloud) {
  42513. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42514. }
  42515. if (defines.SPECULARTERM) {
  42516. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42517. }
  42518. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42519. // Diffuse
  42520. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42521. }
  42522. // Textures
  42523. if (scene.texturesEnabled) {
  42524. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42525. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42526. }
  42527. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42528. effect.setTexture("ambientSampler", this._ambientTexture);
  42529. }
  42530. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42531. effect.setTexture("opacitySampler", this._opacityTexture);
  42532. }
  42533. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42534. if (this._reflectionTexture.isCube) {
  42535. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42536. }
  42537. else {
  42538. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42539. }
  42540. }
  42541. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42542. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42543. }
  42544. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42545. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42546. }
  42547. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42548. effect.setTexture("specularSampler", this._specularTexture);
  42549. }
  42550. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42551. effect.setTexture("bumpSampler", this._bumpTexture);
  42552. }
  42553. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42554. var depth = 1.0;
  42555. if (this._refractionTexture.isCube) {
  42556. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42557. }
  42558. else {
  42559. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42560. }
  42561. }
  42562. }
  42563. // Clip plane
  42564. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42565. // Colors
  42566. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42567. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42568. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42569. }
  42570. if (mustRebind || !this.isFrozen) {
  42571. // Lights
  42572. if (scene.lightsEnabled && !this._disableLighting) {
  42573. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42574. }
  42575. // View
  42576. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42577. this.bindView(effect);
  42578. }
  42579. // Fog
  42580. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42581. // Morph targets
  42582. if (defines.NUM_MORPH_INFLUENCERS) {
  42583. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42584. }
  42585. // Log. depth
  42586. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42587. // image processing
  42588. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42589. this._imageProcessingConfiguration.bind(this._activeEffect);
  42590. }
  42591. }
  42592. this._uniformBuffer.update();
  42593. this._afterBind(mesh, this._activeEffect);
  42594. };
  42595. StandardMaterial.prototype.getAnimatables = function () {
  42596. var results = [];
  42597. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42598. results.push(this._diffuseTexture);
  42599. }
  42600. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42601. results.push(this._ambientTexture);
  42602. }
  42603. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42604. results.push(this._opacityTexture);
  42605. }
  42606. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42607. results.push(this._reflectionTexture);
  42608. }
  42609. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42610. results.push(this._emissiveTexture);
  42611. }
  42612. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42613. results.push(this._specularTexture);
  42614. }
  42615. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42616. results.push(this._bumpTexture);
  42617. }
  42618. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42619. results.push(this._lightmapTexture);
  42620. }
  42621. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42622. results.push(this._refractionTexture);
  42623. }
  42624. return results;
  42625. };
  42626. StandardMaterial.prototype.getActiveTextures = function () {
  42627. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42628. if (this._diffuseTexture) {
  42629. activeTextures.push(this._diffuseTexture);
  42630. }
  42631. if (this._ambientTexture) {
  42632. activeTextures.push(this._ambientTexture);
  42633. }
  42634. if (this._opacityTexture) {
  42635. activeTextures.push(this._opacityTexture);
  42636. }
  42637. if (this._reflectionTexture) {
  42638. activeTextures.push(this._reflectionTexture);
  42639. }
  42640. if (this._emissiveTexture) {
  42641. activeTextures.push(this._emissiveTexture);
  42642. }
  42643. if (this._specularTexture) {
  42644. activeTextures.push(this._specularTexture);
  42645. }
  42646. if (this._bumpTexture) {
  42647. activeTextures.push(this._bumpTexture);
  42648. }
  42649. if (this._lightmapTexture) {
  42650. activeTextures.push(this._lightmapTexture);
  42651. }
  42652. if (this._refractionTexture) {
  42653. activeTextures.push(this._refractionTexture);
  42654. }
  42655. return activeTextures;
  42656. };
  42657. StandardMaterial.prototype.hasTexture = function (texture) {
  42658. if (_super.prototype.hasTexture.call(this, texture)) {
  42659. return true;
  42660. }
  42661. if (this._diffuseTexture === texture) {
  42662. return true;
  42663. }
  42664. if (this._ambientTexture === texture) {
  42665. return true;
  42666. }
  42667. if (this._opacityTexture === texture) {
  42668. return true;
  42669. }
  42670. if (this._reflectionTexture === texture) {
  42671. return true;
  42672. }
  42673. if (this._emissiveTexture === texture) {
  42674. return true;
  42675. }
  42676. if (this._specularTexture === texture) {
  42677. return true;
  42678. }
  42679. if (this._bumpTexture === texture) {
  42680. return true;
  42681. }
  42682. if (this._lightmapTexture === texture) {
  42683. return true;
  42684. }
  42685. if (this._refractionTexture === texture) {
  42686. return true;
  42687. }
  42688. return false;
  42689. };
  42690. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42691. if (forceDisposeTextures) {
  42692. if (this._diffuseTexture) {
  42693. this._diffuseTexture.dispose();
  42694. }
  42695. if (this._ambientTexture) {
  42696. this._ambientTexture.dispose();
  42697. }
  42698. if (this._opacityTexture) {
  42699. this._opacityTexture.dispose();
  42700. }
  42701. if (this._reflectionTexture) {
  42702. this._reflectionTexture.dispose();
  42703. }
  42704. if (this._emissiveTexture) {
  42705. this._emissiveTexture.dispose();
  42706. }
  42707. if (this._specularTexture) {
  42708. this._specularTexture.dispose();
  42709. }
  42710. if (this._bumpTexture) {
  42711. this._bumpTexture.dispose();
  42712. }
  42713. if (this._lightmapTexture) {
  42714. this._lightmapTexture.dispose();
  42715. }
  42716. if (this._refractionTexture) {
  42717. this._refractionTexture.dispose();
  42718. }
  42719. }
  42720. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42721. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42722. }
  42723. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42724. };
  42725. StandardMaterial.prototype.clone = function (name) {
  42726. var _this = this;
  42727. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42728. result.name = name;
  42729. result.id = name;
  42730. return result;
  42731. };
  42732. StandardMaterial.prototype.serialize = function () {
  42733. return BABYLON.SerializationHelper.Serialize(this);
  42734. };
  42735. // Statics
  42736. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42737. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42738. };
  42739. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42740. get: function () {
  42741. return StandardMaterial._DiffuseTextureEnabled;
  42742. },
  42743. set: function (value) {
  42744. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42745. return;
  42746. }
  42747. StandardMaterial._DiffuseTextureEnabled = value;
  42748. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42754. get: function () {
  42755. return StandardMaterial._AmbientTextureEnabled;
  42756. },
  42757. set: function (value) {
  42758. if (StandardMaterial._AmbientTextureEnabled === value) {
  42759. return;
  42760. }
  42761. StandardMaterial._AmbientTextureEnabled = value;
  42762. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42763. },
  42764. enumerable: true,
  42765. configurable: true
  42766. });
  42767. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42768. get: function () {
  42769. return StandardMaterial._OpacityTextureEnabled;
  42770. },
  42771. set: function (value) {
  42772. if (StandardMaterial._OpacityTextureEnabled === value) {
  42773. return;
  42774. }
  42775. StandardMaterial._OpacityTextureEnabled = value;
  42776. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42782. get: function () {
  42783. return StandardMaterial._ReflectionTextureEnabled;
  42784. },
  42785. set: function (value) {
  42786. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42787. return;
  42788. }
  42789. StandardMaterial._ReflectionTextureEnabled = value;
  42790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42791. },
  42792. enumerable: true,
  42793. configurable: true
  42794. });
  42795. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42796. get: function () {
  42797. return StandardMaterial._EmissiveTextureEnabled;
  42798. },
  42799. set: function (value) {
  42800. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42801. return;
  42802. }
  42803. StandardMaterial._EmissiveTextureEnabled = value;
  42804. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42805. },
  42806. enumerable: true,
  42807. configurable: true
  42808. });
  42809. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42810. get: function () {
  42811. return StandardMaterial._SpecularTextureEnabled;
  42812. },
  42813. set: function (value) {
  42814. if (StandardMaterial._SpecularTextureEnabled === value) {
  42815. return;
  42816. }
  42817. StandardMaterial._SpecularTextureEnabled = value;
  42818. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42819. },
  42820. enumerable: true,
  42821. configurable: true
  42822. });
  42823. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42824. get: function () {
  42825. return StandardMaterial._BumpTextureEnabled;
  42826. },
  42827. set: function (value) {
  42828. if (StandardMaterial._BumpTextureEnabled === value) {
  42829. return;
  42830. }
  42831. StandardMaterial._BumpTextureEnabled = value;
  42832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42833. },
  42834. enumerable: true,
  42835. configurable: true
  42836. });
  42837. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42838. get: function () {
  42839. return StandardMaterial._LightmapTextureEnabled;
  42840. },
  42841. set: function (value) {
  42842. if (StandardMaterial._LightmapTextureEnabled === value) {
  42843. return;
  42844. }
  42845. StandardMaterial._LightmapTextureEnabled = value;
  42846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42847. },
  42848. enumerable: true,
  42849. configurable: true
  42850. });
  42851. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42852. get: function () {
  42853. return StandardMaterial._RefractionTextureEnabled;
  42854. },
  42855. set: function (value) {
  42856. if (StandardMaterial._RefractionTextureEnabled === value) {
  42857. return;
  42858. }
  42859. StandardMaterial._RefractionTextureEnabled = value;
  42860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42861. },
  42862. enumerable: true,
  42863. configurable: true
  42864. });
  42865. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42866. get: function () {
  42867. return StandardMaterial._ColorGradingTextureEnabled;
  42868. },
  42869. set: function (value) {
  42870. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42871. return;
  42872. }
  42873. StandardMaterial._ColorGradingTextureEnabled = value;
  42874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42875. },
  42876. enumerable: true,
  42877. configurable: true
  42878. });
  42879. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42880. get: function () {
  42881. return StandardMaterial._FresnelEnabled;
  42882. },
  42883. set: function (value) {
  42884. if (StandardMaterial._FresnelEnabled === value) {
  42885. return;
  42886. }
  42887. StandardMaterial._FresnelEnabled = value;
  42888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42889. },
  42890. enumerable: true,
  42891. configurable: true
  42892. });
  42893. // Flags used to enable or disable a type of texture for all Standard Materials
  42894. StandardMaterial._DiffuseTextureEnabled = true;
  42895. StandardMaterial._AmbientTextureEnabled = true;
  42896. StandardMaterial._OpacityTextureEnabled = true;
  42897. StandardMaterial._ReflectionTextureEnabled = true;
  42898. StandardMaterial._EmissiveTextureEnabled = true;
  42899. StandardMaterial._SpecularTextureEnabled = true;
  42900. StandardMaterial._BumpTextureEnabled = true;
  42901. StandardMaterial._LightmapTextureEnabled = true;
  42902. StandardMaterial._RefractionTextureEnabled = true;
  42903. StandardMaterial._ColorGradingTextureEnabled = true;
  42904. StandardMaterial._FresnelEnabled = true;
  42905. __decorate([
  42906. BABYLON.serializeAsTexture("diffuseTexture")
  42907. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42908. __decorate([
  42909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42910. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42911. __decorate([
  42912. BABYLON.serializeAsTexture("ambientTexture")
  42913. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42914. __decorate([
  42915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42916. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42917. __decorate([
  42918. BABYLON.serializeAsTexture("opacityTexture")
  42919. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42920. __decorate([
  42921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42922. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42923. __decorate([
  42924. BABYLON.serializeAsTexture("reflectionTexture")
  42925. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42926. __decorate([
  42927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42928. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42929. __decorate([
  42930. BABYLON.serializeAsTexture("emissiveTexture")
  42931. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42932. __decorate([
  42933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42934. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42935. __decorate([
  42936. BABYLON.serializeAsTexture("specularTexture")
  42937. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42938. __decorate([
  42939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42940. ], StandardMaterial.prototype, "specularTexture", void 0);
  42941. __decorate([
  42942. BABYLON.serializeAsTexture("bumpTexture")
  42943. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42944. __decorate([
  42945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42946. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42947. __decorate([
  42948. BABYLON.serializeAsTexture("lightmapTexture")
  42949. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42950. __decorate([
  42951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42952. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42953. __decorate([
  42954. BABYLON.serializeAsTexture("refractionTexture")
  42955. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42956. __decorate([
  42957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42958. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42959. __decorate([
  42960. BABYLON.serializeAsColor3("ambient")
  42961. ], StandardMaterial.prototype, "ambientColor", void 0);
  42962. __decorate([
  42963. BABYLON.serializeAsColor3("diffuse")
  42964. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42965. __decorate([
  42966. BABYLON.serializeAsColor3("specular")
  42967. ], StandardMaterial.prototype, "specularColor", void 0);
  42968. __decorate([
  42969. BABYLON.serializeAsColor3("emissive")
  42970. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42971. __decorate([
  42972. BABYLON.serialize()
  42973. ], StandardMaterial.prototype, "specularPower", void 0);
  42974. __decorate([
  42975. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42976. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42977. __decorate([
  42978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42979. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42980. __decorate([
  42981. BABYLON.serialize("useEmissiveAsIllumination")
  42982. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42983. __decorate([
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42985. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42986. __decorate([
  42987. BABYLON.serialize("linkEmissiveWithDiffuse")
  42988. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42989. __decorate([
  42990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42991. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42992. __decorate([
  42993. BABYLON.serialize("useSpecularOverAlpha")
  42994. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42995. __decorate([
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42997. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42998. __decorate([
  42999. BABYLON.serialize("useReflectionOverAlpha")
  43000. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43001. __decorate([
  43002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43003. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43004. __decorate([
  43005. BABYLON.serialize("disableLighting")
  43006. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43007. __decorate([
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43009. ], StandardMaterial.prototype, "disableLighting", void 0);
  43010. __decorate([
  43011. BABYLON.serialize("useObjectSpaceNormalMap")
  43012. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43013. __decorate([
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43015. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43016. __decorate([
  43017. BABYLON.serialize("useParallax")
  43018. ], StandardMaterial.prototype, "_useParallax", void 0);
  43019. __decorate([
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], StandardMaterial.prototype, "useParallax", void 0);
  43022. __decorate([
  43023. BABYLON.serialize("useParallaxOcclusion")
  43024. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43025. __decorate([
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43027. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43028. __decorate([
  43029. BABYLON.serialize()
  43030. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43031. __decorate([
  43032. BABYLON.serialize("roughness")
  43033. ], StandardMaterial.prototype, "_roughness", void 0);
  43034. __decorate([
  43035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43036. ], StandardMaterial.prototype, "roughness", void 0);
  43037. __decorate([
  43038. BABYLON.serialize()
  43039. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43040. __decorate([
  43041. BABYLON.serialize()
  43042. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43043. __decorate([
  43044. BABYLON.serialize()
  43045. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43046. __decorate([
  43047. BABYLON.serialize("useLightmapAsShadowmap")
  43048. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43049. __decorate([
  43050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43051. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43052. __decorate([
  43053. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43054. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43055. __decorate([
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43057. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43058. __decorate([
  43059. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43060. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43061. __decorate([
  43062. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43063. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43064. __decorate([
  43065. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43066. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43067. __decorate([
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43069. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43070. __decorate([
  43071. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43072. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43073. __decorate([
  43074. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43075. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43076. __decorate([
  43077. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43078. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43079. __decorate([
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43081. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43082. __decorate([
  43083. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43084. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43085. __decorate([
  43086. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43087. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43088. __decorate([
  43089. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43090. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43091. __decorate([
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43093. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43094. __decorate([
  43095. BABYLON.serialize("maxSimultaneousLights")
  43096. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43097. __decorate([
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43099. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43100. __decorate([
  43101. BABYLON.serialize("invertNormalMapX")
  43102. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43103. __decorate([
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43106. __decorate([
  43107. BABYLON.serialize("invertNormalMapY")
  43108. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43111. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43112. __decorate([
  43113. BABYLON.serialize("twoSidedLighting")
  43114. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43115. __decorate([
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43118. __decorate([
  43119. BABYLON.serialize()
  43120. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43121. return StandardMaterial;
  43122. }(BABYLON.PushMaterial));
  43123. BABYLON.StandardMaterial = StandardMaterial;
  43124. })(BABYLON || (BABYLON = {}));
  43125. //# sourceMappingURL=babylon.standardMaterial.js.map
  43126. var BABYLON;
  43127. (function (BABYLON) {
  43128. /**
  43129. * Class representing spherical polynomial coefficients to the 3rd degree
  43130. */
  43131. var SphericalPolynomial = /** @class */ (function () {
  43132. function SphericalPolynomial() {
  43133. /**
  43134. * The x coefficients of the spherical polynomial
  43135. */
  43136. this.x = BABYLON.Vector3.Zero();
  43137. /**
  43138. * The y coefficients of the spherical polynomial
  43139. */
  43140. this.y = BABYLON.Vector3.Zero();
  43141. /**
  43142. * The z coefficients of the spherical polynomial
  43143. */
  43144. this.z = BABYLON.Vector3.Zero();
  43145. /**
  43146. * The xx coefficients of the spherical polynomial
  43147. */
  43148. this.xx = BABYLON.Vector3.Zero();
  43149. /**
  43150. * The yy coefficients of the spherical polynomial
  43151. */
  43152. this.yy = BABYLON.Vector3.Zero();
  43153. /**
  43154. * The zz coefficients of the spherical polynomial
  43155. */
  43156. this.zz = BABYLON.Vector3.Zero();
  43157. /**
  43158. * The xy coefficients of the spherical polynomial
  43159. */
  43160. this.xy = BABYLON.Vector3.Zero();
  43161. /**
  43162. * The yz coefficients of the spherical polynomial
  43163. */
  43164. this.yz = BABYLON.Vector3.Zero();
  43165. /**
  43166. * The zx coefficients of the spherical polynomial
  43167. */
  43168. this.zx = BABYLON.Vector3.Zero();
  43169. }
  43170. /**
  43171. * Adds an ambient color to the spherical polynomial
  43172. * @param color the color to add
  43173. */
  43174. SphericalPolynomial.prototype.addAmbient = function (color) {
  43175. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43176. this.xx = this.xx.add(colorVector);
  43177. this.yy = this.yy.add(colorVector);
  43178. this.zz = this.zz.add(colorVector);
  43179. };
  43180. /**
  43181. * Scales the spherical polynomial by the given amount
  43182. * @param scale the amount to scale
  43183. */
  43184. SphericalPolynomial.prototype.scale = function (scale) {
  43185. this.x = this.x.scale(scale);
  43186. this.y = this.y.scale(scale);
  43187. this.z = this.z.scale(scale);
  43188. this.xx = this.xx.scale(scale);
  43189. this.yy = this.yy.scale(scale);
  43190. this.zz = this.zz.scale(scale);
  43191. this.yz = this.yz.scale(scale);
  43192. this.zx = this.zx.scale(scale);
  43193. this.xy = this.xy.scale(scale);
  43194. };
  43195. /**
  43196. * Gets the spherical polynomial from harmonics
  43197. * @param harmonics the spherical harmonics
  43198. * @returns the spherical polynomial
  43199. */
  43200. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43201. var result = new SphericalPolynomial();
  43202. result.x = harmonics.l11.scale(1.02333);
  43203. result.y = harmonics.l1_1.scale(1.02333);
  43204. result.z = harmonics.l10.scale(1.02333);
  43205. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43206. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43207. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43208. result.yz = harmonics.l2_1.scale(0.858086);
  43209. result.zx = harmonics.l21.scale(0.858086);
  43210. result.xy = harmonics.l2_2.scale(0.858086);
  43211. result.scale(1.0 / Math.PI);
  43212. return result;
  43213. };
  43214. /**
  43215. * Constructs a spherical polynomial from an array.
  43216. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43217. * @returns the spherical polynomial
  43218. */
  43219. SphericalPolynomial.FromArray = function (data) {
  43220. var sp = new SphericalPolynomial();
  43221. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43222. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43223. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43224. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43225. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43226. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43227. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43228. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43229. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43230. return sp;
  43231. };
  43232. return SphericalPolynomial;
  43233. }());
  43234. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43235. /**
  43236. * Class representing spherical harmonics coefficients to the 3rd degree
  43237. */
  43238. var SphericalHarmonics = /** @class */ (function () {
  43239. function SphericalHarmonics() {
  43240. /**
  43241. * The l0,0 coefficients of the spherical harmonics
  43242. */
  43243. this.l00 = BABYLON.Vector3.Zero();
  43244. /**
  43245. * The l1,-1 coefficients of the spherical harmonics
  43246. */
  43247. this.l1_1 = BABYLON.Vector3.Zero();
  43248. /**
  43249. * The l1,0 coefficients of the spherical harmonics
  43250. */
  43251. this.l10 = BABYLON.Vector3.Zero();
  43252. /**
  43253. * The l1,1 coefficients of the spherical harmonics
  43254. */
  43255. this.l11 = BABYLON.Vector3.Zero();
  43256. /**
  43257. * The l2,-2 coefficients of the spherical harmonics
  43258. */
  43259. this.l2_2 = BABYLON.Vector3.Zero();
  43260. /**
  43261. * The l2,-1 coefficients of the spherical harmonics
  43262. */
  43263. this.l2_1 = BABYLON.Vector3.Zero();
  43264. /**
  43265. * The l2,0 coefficients of the spherical harmonics
  43266. */
  43267. this.l20 = BABYLON.Vector3.Zero();
  43268. /**
  43269. * The l2,1 coefficients of the spherical harmonics
  43270. */
  43271. this.l21 = BABYLON.Vector3.Zero();
  43272. /**
  43273. * The l2,2 coefficients of the spherical harmonics
  43274. */
  43275. this.lL22 = BABYLON.Vector3.Zero();
  43276. }
  43277. /**
  43278. * Adds a light to the spherical harmonics
  43279. * @param direction the direction of the light
  43280. * @param color the color of the light
  43281. * @param deltaSolidAngle the delta solid angle of the light
  43282. */
  43283. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43284. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43285. var c = colorVector.scale(deltaSolidAngle);
  43286. this.l00 = this.l00.add(c.scale(0.282095));
  43287. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43288. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43289. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43290. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43291. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43292. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43293. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43294. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43295. };
  43296. /**
  43297. * Scales the spherical harmonics by the given amount
  43298. * @param scale the amount to scale
  43299. */
  43300. SphericalHarmonics.prototype.scale = function (scale) {
  43301. this.l00 = this.l00.scale(scale);
  43302. this.l1_1 = this.l1_1.scale(scale);
  43303. this.l10 = this.l10.scale(scale);
  43304. this.l11 = this.l11.scale(scale);
  43305. this.l2_2 = this.l2_2.scale(scale);
  43306. this.l2_1 = this.l2_1.scale(scale);
  43307. this.l20 = this.l20.scale(scale);
  43308. this.l21 = this.l21.scale(scale);
  43309. this.lL22 = this.lL22.scale(scale);
  43310. };
  43311. /**
  43312. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43313. *
  43314. * ```
  43315. * E_lm = A_l * L_lm
  43316. * ```
  43317. *
  43318. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43319. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43320. * the scaling factors are given in equation 9.
  43321. */
  43322. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43323. // Constant (Band 0)
  43324. this.l00 = this.l00.scale(3.141593);
  43325. // Linear (Band 1)
  43326. this.l1_1 = this.l1_1.scale(2.094395);
  43327. this.l10 = this.l10.scale(2.094395);
  43328. this.l11 = this.l11.scale(2.094395);
  43329. // Quadratic (Band 2)
  43330. this.l2_2 = this.l2_2.scale(0.785398);
  43331. this.l2_1 = this.l2_1.scale(0.785398);
  43332. this.l20 = this.l20.scale(0.785398);
  43333. this.l21 = this.l21.scale(0.785398);
  43334. this.lL22 = this.lL22.scale(0.785398);
  43335. };
  43336. /**
  43337. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43338. *
  43339. * ```
  43340. * L = (1/pi) * E * rho
  43341. * ```
  43342. *
  43343. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43344. */
  43345. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43346. this.scale(1.0 / Math.PI);
  43347. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43348. // (The pixel shader must apply albedo after texture fetches, etc).
  43349. };
  43350. /**
  43351. * Gets the spherical harmonics from polynomial
  43352. * @param polynomial the spherical polynomial
  43353. * @returns the spherical harmonics
  43354. */
  43355. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43356. var result = new SphericalHarmonics();
  43357. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43358. result.l1_1 = polynomial.y.scale(0.977204);
  43359. result.l10 = polynomial.z.scale(0.977204);
  43360. result.l11 = polynomial.x.scale(0.977204);
  43361. result.l2_2 = polynomial.xy.scale(1.16538);
  43362. result.l2_1 = polynomial.yz.scale(1.16538);
  43363. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43364. result.l21 = polynomial.zx.scale(1.16538);
  43365. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43366. result.scale(Math.PI);
  43367. return result;
  43368. };
  43369. /**
  43370. * Constructs a spherical harmonics from an array.
  43371. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43372. * @returns the spherical harmonics
  43373. */
  43374. SphericalHarmonics.FromArray = function (data) {
  43375. var sh = new SphericalHarmonics();
  43376. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43377. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43378. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43379. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43380. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43381. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43382. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43383. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43384. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43385. return sh;
  43386. };
  43387. return SphericalHarmonics;
  43388. }());
  43389. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43390. })(BABYLON || (BABYLON = {}));
  43391. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43392. var BABYLON;
  43393. (function (BABYLON) {
  43394. var FileFaceOrientation = /** @class */ (function () {
  43395. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43396. this.name = name;
  43397. this.worldAxisForNormal = worldAxisForNormal;
  43398. this.worldAxisForFileX = worldAxisForFileX;
  43399. this.worldAxisForFileY = worldAxisForFileY;
  43400. }
  43401. return FileFaceOrientation;
  43402. }());
  43403. ;
  43404. /**
  43405. * Helper class dealing with the extraction of spherical polynomial dataArray
  43406. * from a cube map.
  43407. */
  43408. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43409. function CubeMapToSphericalPolynomialTools() {
  43410. }
  43411. /**
  43412. * Converts a texture to the according Spherical Polynomial data.
  43413. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43414. *
  43415. * @param texture The texture to extract the information from.
  43416. * @return The Spherical Polynomial data.
  43417. */
  43418. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43419. if (!texture.isCube) {
  43420. // Only supports cube Textures currently.
  43421. return null;
  43422. }
  43423. var size = texture.getSize().width;
  43424. var right = texture.readPixels(0);
  43425. var left = texture.readPixels(1);
  43426. var up;
  43427. var down;
  43428. if (texture.isRenderTarget) {
  43429. up = texture.readPixels(3);
  43430. down = texture.readPixels(2);
  43431. }
  43432. else {
  43433. up = texture.readPixels(2);
  43434. down = texture.readPixels(3);
  43435. }
  43436. var front = texture.readPixels(4);
  43437. var back = texture.readPixels(5);
  43438. var gammaSpace = texture.gammaSpace;
  43439. // Always read as RGBA.
  43440. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43441. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43442. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43443. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43444. }
  43445. var cubeInfo = {
  43446. size: size,
  43447. right: right,
  43448. left: left,
  43449. up: up,
  43450. down: down,
  43451. front: front,
  43452. back: back,
  43453. format: format,
  43454. type: type,
  43455. gammaSpace: gammaSpace,
  43456. };
  43457. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43458. };
  43459. /**
  43460. * Converts a cubemap to the according Spherical Polynomial data.
  43461. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43462. *
  43463. * @param cubeInfo The Cube map to extract the information from.
  43464. * @return The Spherical Polynomial data.
  43465. */
  43466. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43467. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43468. var totalSolidAngle = 0.0;
  43469. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43470. var du = 2.0 / cubeInfo.size;
  43471. var dv = du;
  43472. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43473. var minUV = du * 0.5 - 1.0;
  43474. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43475. var fileFace = this.FileFaces[faceIndex];
  43476. var dataArray = cubeInfo[fileFace.name];
  43477. var v = minUV;
  43478. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43479. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43480. // Because SP is still linear, so summation is fine in that basis.
  43481. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43482. for (var y = 0; y < cubeInfo.size; y++) {
  43483. var u = minUV;
  43484. for (var x = 0; x < cubeInfo.size; x++) {
  43485. // World direction (not normalised)
  43486. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43487. worldDirection.normalize();
  43488. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43489. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43490. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43491. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43492. // Handle Integer types.
  43493. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43494. r /= 255;
  43495. g /= 255;
  43496. b /= 255;
  43497. }
  43498. // Handle Gamma space textures.
  43499. if (cubeInfo.gammaSpace) {
  43500. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43501. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43502. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43503. }
  43504. var color = new BABYLON.Color3(r, g, b);
  43505. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43506. totalSolidAngle += deltaSolidAngle;
  43507. u += du;
  43508. }
  43509. v += dv;
  43510. }
  43511. }
  43512. // Solid angle for entire sphere is 4*pi
  43513. var sphereSolidAngle = 4.0 * Math.PI;
  43514. // Adjust the solid angle to allow for how many faces we processed.
  43515. var facesProcessed = 6.0;
  43516. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43517. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43518. // This is needed because the numerical integration over the cube uses a
  43519. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43520. // and also to compensate for accumulative error due to float precision in the summation.
  43521. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43522. sphericalHarmonics.scale(correctionFactor);
  43523. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43524. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43525. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43526. };
  43527. CubeMapToSphericalPolynomialTools.FileFaces = [
  43528. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43529. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43530. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43531. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43532. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43533. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43534. ];
  43535. return CubeMapToSphericalPolynomialTools;
  43536. }());
  43537. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43538. })(BABYLON || (BABYLON = {}));
  43539. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43540. var BABYLON;
  43541. (function (BABYLON) {
  43542. /**
  43543. * Manages the defines for the PBR Material.
  43544. * @hiddenChildren
  43545. */
  43546. var PBRMaterialDefines = /** @class */ (function (_super) {
  43547. __extends(PBRMaterialDefines, _super);
  43548. /**
  43549. * Initializes the PBR Material defines.
  43550. */
  43551. function PBRMaterialDefines() {
  43552. var _this = _super.call(this) || this;
  43553. _this.PBR = true;
  43554. _this.MAINUV1 = false;
  43555. _this.MAINUV2 = false;
  43556. _this.UV1 = false;
  43557. _this.UV2 = false;
  43558. _this.ALBEDO = false;
  43559. _this.ALBEDODIRECTUV = 0;
  43560. _this.VERTEXCOLOR = false;
  43561. _this.AMBIENT = false;
  43562. _this.AMBIENTDIRECTUV = 0;
  43563. _this.AMBIENTINGRAYSCALE = false;
  43564. _this.OPACITY = false;
  43565. _this.VERTEXALPHA = false;
  43566. _this.OPACITYDIRECTUV = 0;
  43567. _this.OPACITYRGB = false;
  43568. _this.ALPHATEST = false;
  43569. _this.DEPTHPREPASS = false;
  43570. _this.ALPHABLEND = false;
  43571. _this.ALPHAFROMALBEDO = false;
  43572. _this.ALPHATESTVALUE = "0.5";
  43573. _this.SPECULAROVERALPHA = false;
  43574. _this.RADIANCEOVERALPHA = false;
  43575. _this.ALPHAFRESNEL = false;
  43576. _this.LINEARALPHAFRESNEL = false;
  43577. _this.PREMULTIPLYALPHA = false;
  43578. _this.EMISSIVE = false;
  43579. _this.EMISSIVEDIRECTUV = 0;
  43580. _this.REFLECTIVITY = false;
  43581. _this.REFLECTIVITYDIRECTUV = 0;
  43582. _this.SPECULARTERM = false;
  43583. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43584. _this.MICROSURFACEAUTOMATIC = false;
  43585. _this.LODBASEDMICROSFURACE = false;
  43586. _this.MICROSURFACEMAP = false;
  43587. _this.MICROSURFACEMAPDIRECTUV = 0;
  43588. _this.METALLICWORKFLOW = false;
  43589. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43590. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43591. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43592. _this.AOSTOREINMETALMAPRED = false;
  43593. _this.ENVIRONMENTBRDF = false;
  43594. _this.NORMAL = false;
  43595. _this.TANGENT = false;
  43596. _this.BUMP = false;
  43597. _this.BUMPDIRECTUV = 0;
  43598. _this.OBJECTSPACE_NORMALMAP = false;
  43599. _this.PARALLAX = false;
  43600. _this.PARALLAXOCCLUSION = false;
  43601. _this.NORMALXYSCALE = true;
  43602. _this.LIGHTMAP = false;
  43603. _this.LIGHTMAPDIRECTUV = 0;
  43604. _this.USELIGHTMAPASSHADOWMAP = false;
  43605. _this.GAMMALIGHTMAP = false;
  43606. _this.REFLECTION = false;
  43607. _this.REFLECTIONMAP_3D = false;
  43608. _this.REFLECTIONMAP_SPHERICAL = false;
  43609. _this.REFLECTIONMAP_PLANAR = false;
  43610. _this.REFLECTIONMAP_CUBIC = false;
  43611. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43612. _this.REFLECTIONMAP_PROJECTION = false;
  43613. _this.REFLECTIONMAP_SKYBOX = false;
  43614. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43615. _this.REFLECTIONMAP_EXPLICIT = false;
  43616. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43617. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43618. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43619. _this.INVERTCUBICMAP = false;
  43620. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43621. _this.USESPHERICALINVERTEX = false;
  43622. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43623. _this.LODINREFLECTIONALPHA = false;
  43624. _this.GAMMAREFLECTION = false;
  43625. _this.RGBDREFLECTION = false;
  43626. _this.RADIANCEOCCLUSION = false;
  43627. _this.HORIZONOCCLUSION = false;
  43628. _this.REFRACTION = false;
  43629. _this.REFRACTIONMAP_3D = false;
  43630. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43631. _this.LODINREFRACTIONALPHA = false;
  43632. _this.GAMMAREFRACTION = false;
  43633. _this.RGBDREFRACTION = false;
  43634. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43635. _this.INSTANCES = false;
  43636. _this.NUM_BONE_INFLUENCERS = 0;
  43637. _this.BonesPerMesh = 0;
  43638. _this.NONUNIFORMSCALING = false;
  43639. _this.MORPHTARGETS = false;
  43640. _this.MORPHTARGETS_NORMAL = false;
  43641. _this.MORPHTARGETS_TANGENT = false;
  43642. _this.NUM_MORPH_INFLUENCERS = 0;
  43643. _this.IMAGEPROCESSING = false;
  43644. _this.VIGNETTE = false;
  43645. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43646. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43647. _this.TONEMAPPING = false;
  43648. _this.TONEMAPPING_ACES = false;
  43649. _this.CONTRAST = false;
  43650. _this.COLORCURVES = false;
  43651. _this.COLORGRADING = false;
  43652. _this.COLORGRADING3D = false;
  43653. _this.SAMPLER3DGREENDEPTH = false;
  43654. _this.SAMPLER3DBGRMAP = false;
  43655. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43656. _this.EXPOSURE = false;
  43657. _this.USEPHYSICALLIGHTFALLOFF = false;
  43658. _this.USEGLTFLIGHTFALLOFF = false;
  43659. _this.TWOSIDEDLIGHTING = false;
  43660. _this.SHADOWFLOAT = false;
  43661. _this.CLIPPLANE = false;
  43662. _this.CLIPPLANE2 = false;
  43663. _this.CLIPPLANE3 = false;
  43664. _this.CLIPPLANE4 = false;
  43665. _this.POINTSIZE = false;
  43666. _this.FOG = false;
  43667. _this.LOGARITHMICDEPTH = false;
  43668. _this.FORCENORMALFORWARD = false;
  43669. _this.SPECULARAA = false;
  43670. _this.UNLIT = false;
  43671. _this.rebuild();
  43672. return _this;
  43673. }
  43674. /**
  43675. * Resets the PBR Material defines.
  43676. */
  43677. PBRMaterialDefines.prototype.reset = function () {
  43678. _super.prototype.reset.call(this);
  43679. this.ALPHATESTVALUE = "0.5";
  43680. this.PBR = true;
  43681. };
  43682. return PBRMaterialDefines;
  43683. }(BABYLON.MaterialDefines));
  43684. /**
  43685. * The Physically based material base class of BJS.
  43686. *
  43687. * This offers the main features of a standard PBR material.
  43688. * For more information, please refer to the documentation :
  43689. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43690. */
  43691. var PBRBaseMaterial = /** @class */ (function (_super) {
  43692. __extends(PBRBaseMaterial, _super);
  43693. /**
  43694. * Instantiates a new PBRMaterial instance.
  43695. *
  43696. * @param name The material name
  43697. * @param scene The scene the material will be use in.
  43698. */
  43699. function PBRBaseMaterial(name, scene) {
  43700. var _this = _super.call(this, name, scene) || this;
  43701. /**
  43702. * Intensity of the direct lights e.g. the four lights available in your scene.
  43703. * This impacts both the direct diffuse and specular highlights.
  43704. */
  43705. _this._directIntensity = 1.0;
  43706. /**
  43707. * Intensity of the emissive part of the material.
  43708. * This helps controlling the emissive effect without modifying the emissive color.
  43709. */
  43710. _this._emissiveIntensity = 1.0;
  43711. /**
  43712. * Intensity of the environment e.g. how much the environment will light the object
  43713. * either through harmonics for rough material or through the refelction for shiny ones.
  43714. */
  43715. _this._environmentIntensity = 1.0;
  43716. /**
  43717. * This is a special control allowing the reduction of the specular highlights coming from the
  43718. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43719. */
  43720. _this._specularIntensity = 1.0;
  43721. /**
  43722. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43723. */
  43724. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43725. /**
  43726. * Debug Control allowing disabling the bump map on this material.
  43727. */
  43728. _this._disableBumpMap = false;
  43729. /**
  43730. * AKA Occlusion Texture Intensity in other nomenclature.
  43731. */
  43732. _this._ambientTextureStrength = 1.0;
  43733. /**
  43734. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43735. * 1 means it completely occludes it
  43736. * 0 mean it has no impact
  43737. */
  43738. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43739. /**
  43740. * The color of a material in ambient lighting.
  43741. */
  43742. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43743. /**
  43744. * AKA Diffuse Color in other nomenclature.
  43745. */
  43746. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43747. /**
  43748. * AKA Specular Color in other nomenclature.
  43749. */
  43750. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43751. /**
  43752. * The color applied when light is reflected from a material.
  43753. */
  43754. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43755. /**
  43756. * The color applied when light is emitted from a material.
  43757. */
  43758. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43759. /**
  43760. * AKA Glossiness in other nomenclature.
  43761. */
  43762. _this._microSurface = 0.9;
  43763. /**
  43764. * source material index of refraction (IOR)' / 'destination material IOR.
  43765. */
  43766. _this._indexOfRefraction = 0.66;
  43767. /**
  43768. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43769. */
  43770. _this._invertRefractionY = false;
  43771. /**
  43772. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43773. * Materials half opaque for instance using refraction could benefit from this control.
  43774. */
  43775. _this._linkRefractionWithTransparency = false;
  43776. /**
  43777. * Specifies that the material will use the light map as a show map.
  43778. */
  43779. _this._useLightmapAsShadowmap = false;
  43780. /**
  43781. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43782. * makes the reflect vector face the model (under horizon).
  43783. */
  43784. _this._useHorizonOcclusion = true;
  43785. /**
  43786. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43787. * too much the area relying on ambient texture to define their ambient occlusion.
  43788. */
  43789. _this._useRadianceOcclusion = true;
  43790. /**
  43791. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43792. */
  43793. _this._useAlphaFromAlbedoTexture = false;
  43794. /**
  43795. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43796. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43797. */
  43798. _this._useSpecularOverAlpha = true;
  43799. /**
  43800. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43801. */
  43802. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43803. /**
  43804. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43805. */
  43806. _this._useRoughnessFromMetallicTextureAlpha = true;
  43807. /**
  43808. * Specifies if the metallic texture contains the roughness information in its green channel.
  43809. */
  43810. _this._useRoughnessFromMetallicTextureGreen = false;
  43811. /**
  43812. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43813. */
  43814. _this._useMetallnessFromMetallicTextureBlue = false;
  43815. /**
  43816. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43817. */
  43818. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43819. /**
  43820. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43821. */
  43822. _this._useAmbientInGrayScale = false;
  43823. /**
  43824. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43825. * The material will try to infer what glossiness each pixel should be.
  43826. */
  43827. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43828. /**
  43829. * Defines the falloff type used in this material.
  43830. * It by default is Physical.
  43831. */
  43832. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43833. /**
  43834. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43835. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43836. */
  43837. _this._useRadianceOverAlpha = true;
  43838. /**
  43839. * Allows using an object space normal map (instead of tangent space).
  43840. */
  43841. _this._useObjectSpaceNormalMap = false;
  43842. /**
  43843. * Allows using the bump map in parallax mode.
  43844. */
  43845. _this._useParallax = false;
  43846. /**
  43847. * Allows using the bump map in parallax occlusion mode.
  43848. */
  43849. _this._useParallaxOcclusion = false;
  43850. /**
  43851. * Controls the scale bias of the parallax mode.
  43852. */
  43853. _this._parallaxScaleBias = 0.05;
  43854. /**
  43855. * If sets to true, disables all the lights affecting the material.
  43856. */
  43857. _this._disableLighting = false;
  43858. /**
  43859. * Number of Simultaneous lights allowed on the material.
  43860. */
  43861. _this._maxSimultaneousLights = 4;
  43862. /**
  43863. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43864. */
  43865. _this._invertNormalMapX = false;
  43866. /**
  43867. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43868. */
  43869. _this._invertNormalMapY = false;
  43870. /**
  43871. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43872. */
  43873. _this._twoSidedLighting = false;
  43874. /**
  43875. * Defines the alpha limits in alpha test mode.
  43876. */
  43877. _this._alphaCutOff = 0.4;
  43878. /**
  43879. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43880. */
  43881. _this._forceAlphaTest = false;
  43882. /**
  43883. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43884. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43885. */
  43886. _this._useAlphaFresnel = false;
  43887. /**
  43888. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43889. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43890. */
  43891. _this._useLinearAlphaFresnel = false;
  43892. /**
  43893. * The transparency mode of the material.
  43894. */
  43895. _this._transparencyMode = null;
  43896. /**
  43897. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43898. * from cos thetav and roughness:
  43899. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43900. */
  43901. _this._environmentBRDFTexture = null;
  43902. /**
  43903. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43904. */
  43905. _this._forceIrradianceInFragment = false;
  43906. /**
  43907. * Force normal to face away from face.
  43908. */
  43909. _this._forceNormalForward = false;
  43910. /**
  43911. * Enables specular anti aliasing in the PBR shader.
  43912. * It will both interacts on the Geometry for analytical and IBL lighting.
  43913. * It also prefilter the roughness map based on the bump values.
  43914. */
  43915. _this._enableSpecularAntiAliasing = false;
  43916. /**
  43917. * Stores the available render targets.
  43918. */
  43919. _this._renderTargets = new BABYLON.SmartArray(16);
  43920. /**
  43921. * Sets the global ambient color for the material used in lighting calculations.
  43922. */
  43923. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43924. /**
  43925. * If set to true, no lighting calculations will be applied.
  43926. */
  43927. _this._unlit = false;
  43928. // Setup the default processing configuration to the scene.
  43929. _this._attachImageProcessingConfiguration(null);
  43930. _this.getRenderTargetTextures = function () {
  43931. _this._renderTargets.reset();
  43932. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43933. _this._renderTargets.push(_this._reflectionTexture);
  43934. }
  43935. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43936. _this._renderTargets.push(_this._refractionTexture);
  43937. }
  43938. return _this._renderTargets;
  43939. };
  43940. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43941. return _this;
  43942. }
  43943. /**
  43944. * Attaches a new image processing configuration to the PBR Material.
  43945. * @param configuration
  43946. */
  43947. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43948. var _this = this;
  43949. if (configuration === this._imageProcessingConfiguration) {
  43950. return;
  43951. }
  43952. // Detaches observer.
  43953. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43954. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43955. }
  43956. // Pick the scene configuration if needed.
  43957. if (!configuration) {
  43958. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43959. }
  43960. else {
  43961. this._imageProcessingConfiguration = configuration;
  43962. }
  43963. // Attaches observer.
  43964. if (this._imageProcessingConfiguration) {
  43965. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43966. _this._markAllSubMeshesAsImageProcessingDirty();
  43967. });
  43968. }
  43969. };
  43970. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43971. /**
  43972. * Gets a boolean indicating that current material needs to register RTT
  43973. */
  43974. get: function () {
  43975. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43976. return true;
  43977. }
  43978. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43979. return true;
  43980. }
  43981. return false;
  43982. },
  43983. enumerable: true,
  43984. configurable: true
  43985. });
  43986. /**
  43987. * Gets the name of the material class.
  43988. */
  43989. PBRBaseMaterial.prototype.getClassName = function () {
  43990. return "PBRBaseMaterial";
  43991. };
  43992. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43993. /**
  43994. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43995. */
  43996. get: function () {
  43997. return this._useLogarithmicDepth;
  43998. },
  43999. /**
  44000. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44001. */
  44002. set: function (value) {
  44003. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44004. },
  44005. enumerable: true,
  44006. configurable: true
  44007. });
  44008. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44009. /**
  44010. * Gets the current transparency mode.
  44011. */
  44012. get: function () {
  44013. return this._transparencyMode;
  44014. },
  44015. /**
  44016. * Sets the transparency mode of the material.
  44017. *
  44018. * | Value | Type | Description |
  44019. * | ----- | ----------------------------------- | ----------- |
  44020. * | 0 | OPAQUE | |
  44021. * | 1 | ALPHATEST | |
  44022. * | 2 | ALPHABLEND | |
  44023. * | 3 | ALPHATESTANDBLEND | |
  44024. *
  44025. */
  44026. set: function (value) {
  44027. if (this._transparencyMode === value) {
  44028. return;
  44029. }
  44030. this._transparencyMode = value;
  44031. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44032. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44033. },
  44034. enumerable: true,
  44035. configurable: true
  44036. });
  44037. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44038. /**
  44039. * Returns true if alpha blending should be disabled.
  44040. */
  44041. get: function () {
  44042. return (this._linkRefractionWithTransparency ||
  44043. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44044. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44045. },
  44046. enumerable: true,
  44047. configurable: true
  44048. });
  44049. /**
  44050. * Specifies whether or not this material should be rendered in alpha blend mode.
  44051. */
  44052. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44053. if (this._disableAlphaBlending) {
  44054. return false;
  44055. }
  44056. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44057. };
  44058. /**
  44059. * Specifies if the mesh will require alpha blending.
  44060. * @param mesh - BJS mesh.
  44061. */
  44062. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44063. if (this._disableAlphaBlending) {
  44064. return false;
  44065. }
  44066. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44067. };
  44068. /**
  44069. * Specifies whether or not this material should be rendered in alpha test mode.
  44070. */
  44071. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44072. if (this._forceAlphaTest) {
  44073. return true;
  44074. }
  44075. if (this._linkRefractionWithTransparency) {
  44076. return false;
  44077. }
  44078. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44079. };
  44080. /**
  44081. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44082. */
  44083. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44084. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44085. };
  44086. /**
  44087. * Gets the texture used for the alpha test.
  44088. */
  44089. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44090. return this._albedoTexture;
  44091. };
  44092. /**
  44093. * Specifies that the submesh is ready to be used.
  44094. * @param mesh - BJS mesh.
  44095. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44096. * @param useInstances - Specifies that instances should be used.
  44097. * @returns - boolean indicating that the submesh is ready or not.
  44098. */
  44099. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44100. if (subMesh.effect && this.isFrozen) {
  44101. if (this._wasPreviouslyReady) {
  44102. return true;
  44103. }
  44104. }
  44105. if (!subMesh._materialDefines) {
  44106. subMesh._materialDefines = new PBRMaterialDefines();
  44107. }
  44108. var defines = subMesh._materialDefines;
  44109. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44110. if (defines._renderId === this.getScene().getRenderId()) {
  44111. return true;
  44112. }
  44113. }
  44114. var scene = this.getScene();
  44115. var engine = scene.getEngine();
  44116. if (defines._areTexturesDirty) {
  44117. if (scene.texturesEnabled) {
  44118. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44119. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44120. return false;
  44121. }
  44122. }
  44123. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44124. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44125. return false;
  44126. }
  44127. }
  44128. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44129. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44130. return false;
  44131. }
  44132. }
  44133. var reflectionTexture = this._getReflectionTexture();
  44134. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44135. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44136. return false;
  44137. }
  44138. }
  44139. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44140. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44141. return false;
  44142. }
  44143. }
  44144. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44145. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44146. return false;
  44147. }
  44148. }
  44149. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44150. if (this._metallicTexture) {
  44151. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44152. return false;
  44153. }
  44154. }
  44155. else if (this._reflectivityTexture) {
  44156. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44157. return false;
  44158. }
  44159. }
  44160. if (this._microSurfaceTexture) {
  44161. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44162. return false;
  44163. }
  44164. }
  44165. }
  44166. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44167. // Bump texture cannot be not blocking.
  44168. if (!this._bumpTexture.isReady()) {
  44169. return false;
  44170. }
  44171. }
  44172. var refractionTexture = this._getRefractionTexture();
  44173. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44174. if (!refractionTexture.isReadyOrNotBlocking()) {
  44175. return false;
  44176. }
  44177. }
  44178. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44179. // This is blocking.
  44180. if (!this._environmentBRDFTexture.isReady()) {
  44181. return false;
  44182. }
  44183. }
  44184. }
  44185. }
  44186. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44187. if (!this._imageProcessingConfiguration.isReady()) {
  44188. return false;
  44189. }
  44190. }
  44191. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44192. mesh.createNormals(true);
  44193. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44194. }
  44195. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44196. if (effect) {
  44197. scene.resetCachedMaterial();
  44198. subMesh.setEffect(effect, defines);
  44199. this.buildUniformLayout();
  44200. }
  44201. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44202. return false;
  44203. }
  44204. defines._renderId = scene.getRenderId();
  44205. this._wasPreviouslyReady = true;
  44206. return true;
  44207. };
  44208. /**
  44209. * Specifies if the material uses metallic roughness workflow.
  44210. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44211. */
  44212. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44213. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44214. return true;
  44215. }
  44216. return false;
  44217. };
  44218. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44219. if (onCompiled === void 0) { onCompiled = null; }
  44220. if (onError === void 0) { onError = null; }
  44221. if (useInstances === void 0) { useInstances = null; }
  44222. if (useClipPlane === void 0) { useClipPlane = null; }
  44223. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44224. if (!defines.isDirty) {
  44225. return null;
  44226. }
  44227. defines.markAsProcessed();
  44228. var scene = this.getScene();
  44229. var engine = scene.getEngine();
  44230. // Fallbacks
  44231. var fallbacks = new BABYLON.EffectFallbacks();
  44232. var fallbackRank = 0;
  44233. if (defines.USESPHERICALINVERTEX) {
  44234. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44235. }
  44236. if (defines.FOG) {
  44237. fallbacks.addFallback(fallbackRank, "FOG");
  44238. }
  44239. if (defines.SPECULARAA) {
  44240. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44241. }
  44242. if (defines.POINTSIZE) {
  44243. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44244. }
  44245. if (defines.LOGARITHMICDEPTH) {
  44246. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44247. }
  44248. if (defines.PARALLAX) {
  44249. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44250. }
  44251. if (defines.PARALLAXOCCLUSION) {
  44252. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44253. }
  44254. if (defines.ENVIRONMENTBRDF) {
  44255. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44256. }
  44257. if (defines.TANGENT) {
  44258. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44259. }
  44260. if (defines.BUMP) {
  44261. fallbacks.addFallback(fallbackRank++, "BUMP");
  44262. }
  44263. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44264. if (defines.SPECULARTERM) {
  44265. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44266. }
  44267. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44268. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44269. }
  44270. if (defines.LIGHTMAP) {
  44271. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44272. }
  44273. if (defines.NORMAL) {
  44274. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44275. }
  44276. if (defines.AMBIENT) {
  44277. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44278. }
  44279. if (defines.EMISSIVE) {
  44280. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44281. }
  44282. if (defines.VERTEXCOLOR) {
  44283. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44284. }
  44285. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44286. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44287. }
  44288. if (defines.MORPHTARGETS) {
  44289. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44290. }
  44291. //Attributes
  44292. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44293. if (defines.NORMAL) {
  44294. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44295. }
  44296. if (defines.TANGENT) {
  44297. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44298. }
  44299. if (defines.UV1) {
  44300. attribs.push(BABYLON.VertexBuffer.UVKind);
  44301. }
  44302. if (defines.UV2) {
  44303. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44304. }
  44305. if (defines.VERTEXCOLOR) {
  44306. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44307. }
  44308. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44309. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44310. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44311. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44312. "vFogInfos", "vFogColor", "pointSize",
  44313. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44314. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44315. "mBones",
  44316. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44317. "vLightingIntensity",
  44318. "logarithmicDepthConstant",
  44319. "vSphericalX", "vSphericalY", "vSphericalZ",
  44320. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44321. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44322. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44323. "vTangentSpaceParams"
  44324. ];
  44325. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44326. "bumpSampler", "lightmapSampler", "opacitySampler",
  44327. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44328. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44329. "microSurfaceSampler", "environmentBrdfSampler"];
  44330. var uniformBuffers = ["Material", "Scene"];
  44331. if (BABYLON.ImageProcessingConfiguration) {
  44332. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44333. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44334. }
  44335. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44336. uniformsNames: uniforms,
  44337. uniformBuffersNames: uniformBuffers,
  44338. samplers: samplers,
  44339. defines: defines,
  44340. maxSimultaneousLights: this._maxSimultaneousLights
  44341. });
  44342. var join = defines.toString();
  44343. return engine.createEffect("pbr", {
  44344. attributes: attribs,
  44345. uniformsNames: uniforms,
  44346. uniformBuffersNames: uniformBuffers,
  44347. samplers: samplers,
  44348. defines: join,
  44349. fallbacks: fallbacks,
  44350. onCompiled: onCompiled,
  44351. onError: onError,
  44352. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44353. }, engine);
  44354. };
  44355. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44356. if (useInstances === void 0) { useInstances = null; }
  44357. if (useClipPlane === void 0) { useClipPlane = null; }
  44358. var scene = this.getScene();
  44359. var engine = scene.getEngine();
  44360. // Lights
  44361. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44362. defines._needNormals = true;
  44363. // Textures
  44364. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44365. if (defines._areTexturesDirty) {
  44366. defines._needUVs = false;
  44367. if (scene.texturesEnabled) {
  44368. if (scene.getEngine().getCaps().textureLOD) {
  44369. defines.LODBASEDMICROSFURACE = true;
  44370. }
  44371. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44372. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44373. }
  44374. else {
  44375. defines.ALBEDO = false;
  44376. }
  44377. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44378. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44379. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44380. }
  44381. else {
  44382. defines.AMBIENT = false;
  44383. }
  44384. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44385. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44386. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44387. }
  44388. else {
  44389. defines.OPACITY = false;
  44390. }
  44391. var reflectionTexture = this._getReflectionTexture();
  44392. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44393. defines.REFLECTION = true;
  44394. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44395. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44396. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44397. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44398. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44399. defines.INVERTCUBICMAP = true;
  44400. }
  44401. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44402. switch (reflectionTexture.coordinatesMode) {
  44403. case BABYLON.Texture.EXPLICIT_MODE:
  44404. defines.REFLECTIONMAP_EXPLICIT = true;
  44405. break;
  44406. case BABYLON.Texture.PLANAR_MODE:
  44407. defines.REFLECTIONMAP_PLANAR = true;
  44408. break;
  44409. case BABYLON.Texture.PROJECTION_MODE:
  44410. defines.REFLECTIONMAP_PROJECTION = true;
  44411. break;
  44412. case BABYLON.Texture.SKYBOX_MODE:
  44413. defines.REFLECTIONMAP_SKYBOX = true;
  44414. break;
  44415. case BABYLON.Texture.SPHERICAL_MODE:
  44416. defines.REFLECTIONMAP_SPHERICAL = true;
  44417. break;
  44418. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44419. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44420. break;
  44421. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44422. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44423. break;
  44424. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44425. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44426. break;
  44427. case BABYLON.Texture.CUBIC_MODE:
  44428. case BABYLON.Texture.INVCUBIC_MODE:
  44429. default:
  44430. defines.REFLECTIONMAP_CUBIC = true;
  44431. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44432. break;
  44433. }
  44434. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44435. if (reflectionTexture.sphericalPolynomial) {
  44436. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44437. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44438. defines.USESPHERICALINVERTEX = false;
  44439. }
  44440. else {
  44441. defines.USESPHERICALINVERTEX = true;
  44442. }
  44443. }
  44444. }
  44445. else {
  44446. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44447. }
  44448. }
  44449. else {
  44450. defines.REFLECTION = false;
  44451. defines.REFLECTIONMAP_3D = false;
  44452. defines.REFLECTIONMAP_SPHERICAL = false;
  44453. defines.REFLECTIONMAP_PLANAR = false;
  44454. defines.REFLECTIONMAP_CUBIC = false;
  44455. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44456. defines.REFLECTIONMAP_PROJECTION = false;
  44457. defines.REFLECTIONMAP_SKYBOX = false;
  44458. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44459. defines.REFLECTIONMAP_EXPLICIT = false;
  44460. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44461. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44462. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44463. defines.INVERTCUBICMAP = false;
  44464. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44465. defines.USESPHERICALINVERTEX = false;
  44466. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44467. defines.LODINREFLECTIONALPHA = false;
  44468. defines.GAMMAREFLECTION = false;
  44469. defines.RGBDREFLECTION = false;
  44470. }
  44471. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44473. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44474. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44475. }
  44476. else {
  44477. defines.LIGHTMAP = false;
  44478. }
  44479. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44480. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44481. }
  44482. else {
  44483. defines.EMISSIVE = false;
  44484. }
  44485. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44486. if (this._metallicTexture) {
  44487. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44488. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44489. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44490. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44491. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44492. }
  44493. else if (this._reflectivityTexture) {
  44494. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44495. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44496. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44497. }
  44498. else {
  44499. defines.REFLECTIVITY = false;
  44500. }
  44501. if (this._microSurfaceTexture) {
  44502. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44503. }
  44504. else {
  44505. defines.MICROSURFACEMAP = false;
  44506. }
  44507. }
  44508. else {
  44509. defines.REFLECTIVITY = false;
  44510. defines.MICROSURFACEMAP = false;
  44511. }
  44512. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44513. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44514. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44515. defines.PARALLAX = true;
  44516. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44517. }
  44518. else {
  44519. defines.PARALLAX = false;
  44520. }
  44521. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44522. }
  44523. else {
  44524. defines.BUMP = false;
  44525. }
  44526. var refractionTexture = this._getRefractionTexture();
  44527. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44528. defines.REFRACTION = true;
  44529. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44530. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44531. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44532. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44533. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44534. if (this._linkRefractionWithTransparency) {
  44535. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44536. }
  44537. }
  44538. else {
  44539. defines.REFRACTION = false;
  44540. }
  44541. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44542. defines.ENVIRONMENTBRDF = true;
  44543. }
  44544. else {
  44545. defines.ENVIRONMENTBRDF = false;
  44546. }
  44547. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44548. defines.ALPHAFROMALBEDO = true;
  44549. }
  44550. else {
  44551. defines.ALPHAFROMALBEDO = false;
  44552. }
  44553. }
  44554. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44555. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44556. defines.USEPHYSICALLIGHTFALLOFF = false;
  44557. defines.USEGLTFLIGHTFALLOFF = false;
  44558. }
  44559. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44560. defines.USEPHYSICALLIGHTFALLOFF = false;
  44561. defines.USEGLTFLIGHTFALLOFF = true;
  44562. }
  44563. else {
  44564. defines.USEPHYSICALLIGHTFALLOFF = true;
  44565. defines.USEGLTFLIGHTFALLOFF = false;
  44566. }
  44567. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44568. if (!this.backFaceCulling && this._twoSidedLighting) {
  44569. defines.TWOSIDEDLIGHTING = true;
  44570. }
  44571. else {
  44572. defines.TWOSIDEDLIGHTING = false;
  44573. }
  44574. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44575. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44576. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44577. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44578. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44579. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44580. }
  44581. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44582. this._imageProcessingConfiguration.prepareDefines(defines);
  44583. }
  44584. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44585. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44586. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44587. // Misc.
  44588. if (defines._areMiscDirty) {
  44589. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44590. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44591. }
  44592. // Values that need to be evaluated on every frame
  44593. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44594. // Attribs
  44595. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44596. };
  44597. /**
  44598. * Force shader compilation
  44599. */
  44600. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44601. var _this = this;
  44602. var localOptions = __assign({ clipPlane: false }, options);
  44603. var defines = new PBRMaterialDefines();
  44604. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44605. if (effect.isReady()) {
  44606. if (onCompiled) {
  44607. onCompiled(this);
  44608. }
  44609. }
  44610. else {
  44611. effect.onCompileObservable.add(function () {
  44612. if (onCompiled) {
  44613. onCompiled(_this);
  44614. }
  44615. });
  44616. }
  44617. };
  44618. /**
  44619. * Initializes the uniform buffer layout for the shader.
  44620. */
  44621. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44622. // Order is important !
  44623. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44624. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44625. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44626. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44627. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44628. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44629. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44630. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44631. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44632. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44633. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44634. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44635. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44636. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44637. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44638. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44639. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44640. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44641. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44642. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44643. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44644. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44645. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44646. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44647. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44648. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44649. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44650. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44651. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44652. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44653. this._uniformBuffer.addUniform("pointSize", 1);
  44654. this._uniformBuffer.create();
  44655. };
  44656. /**
  44657. * Unbinds the textures.
  44658. */
  44659. PBRBaseMaterial.prototype.unbind = function () {
  44660. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44661. this._uniformBuffer.setTexture("reflectionSampler", null);
  44662. }
  44663. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44664. this._uniformBuffer.setTexture("refractionSampler", null);
  44665. }
  44666. _super.prototype.unbind.call(this);
  44667. };
  44668. /**
  44669. * Binds the submesh data.
  44670. * @param world - The world matrix.
  44671. * @param mesh - The BJS mesh.
  44672. * @param subMesh - A submesh of the BJS mesh.
  44673. */
  44674. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44675. var scene = this.getScene();
  44676. var defines = subMesh._materialDefines;
  44677. if (!defines) {
  44678. return;
  44679. }
  44680. var effect = subMesh.effect;
  44681. if (!effect) {
  44682. return;
  44683. }
  44684. this._activeEffect = effect;
  44685. // Matrices
  44686. this.bindOnlyWorldMatrix(world);
  44687. // Normal Matrix
  44688. if (defines.OBJECTSPACE_NORMALMAP) {
  44689. world.toNormalMatrix(this._normalMatrix);
  44690. this.bindOnlyNormalMatrix(this._normalMatrix);
  44691. }
  44692. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44693. // Bones
  44694. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44695. var reflectionTexture = null;
  44696. if (mustRebind) {
  44697. this._uniformBuffer.bindToEffect(effect, "Material");
  44698. this.bindViewProjection(effect);
  44699. reflectionTexture = this._getReflectionTexture();
  44700. var refractionTexture = this._getRefractionTexture();
  44701. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44702. // Texture uniforms
  44703. if (scene.texturesEnabled) {
  44704. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44705. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44706. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44707. }
  44708. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44709. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44710. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44711. }
  44712. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44713. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44714. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44715. }
  44716. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44717. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44718. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44719. if (reflectionTexture.boundingBoxSize) {
  44720. var cubeTexture = reflectionTexture;
  44721. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44722. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44723. }
  44724. var polynomials = reflectionTexture.sphericalPolynomial;
  44725. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44726. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44727. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44728. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44729. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44730. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44731. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44732. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44733. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44734. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44735. }
  44736. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44737. }
  44738. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44739. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44740. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44741. }
  44742. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44743. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44744. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44745. }
  44746. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44747. if (this._metallicTexture) {
  44748. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44749. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44750. }
  44751. else if (this._reflectivityTexture) {
  44752. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44753. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44754. }
  44755. if (this._microSurfaceTexture) {
  44756. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44757. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44758. }
  44759. }
  44760. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44761. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44762. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44763. if (scene._mirroredCameraPosition) {
  44764. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44765. }
  44766. else {
  44767. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44768. }
  44769. }
  44770. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44771. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44772. var depth = 1.0;
  44773. if (!refractionTexture.isCube) {
  44774. if (refractionTexture.depth) {
  44775. depth = refractionTexture.depth;
  44776. }
  44777. }
  44778. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44779. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44780. }
  44781. }
  44782. // Point size
  44783. if (this.pointsCloud) {
  44784. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44785. }
  44786. // Colors
  44787. if (defines.METALLICWORKFLOW) {
  44788. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44789. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44790. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44791. }
  44792. else {
  44793. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44794. }
  44795. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44796. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44797. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44798. // Misc
  44799. this._lightingInfos.x = this._directIntensity;
  44800. this._lightingInfos.y = this._emissiveIntensity;
  44801. this._lightingInfos.z = this._environmentIntensity;
  44802. this._lightingInfos.w = this._specularIntensity;
  44803. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44804. }
  44805. // Textures
  44806. if (scene.texturesEnabled) {
  44807. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44808. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44809. }
  44810. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44811. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44812. }
  44813. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44814. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44815. }
  44816. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44817. if (defines.LODBASEDMICROSFURACE) {
  44818. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44819. }
  44820. else {
  44821. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44822. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44823. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44824. }
  44825. }
  44826. if (defines.ENVIRONMENTBRDF) {
  44827. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44828. }
  44829. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44830. if (defines.LODBASEDMICROSFURACE) {
  44831. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44832. }
  44833. else {
  44834. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44835. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44836. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44837. }
  44838. }
  44839. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44840. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44841. }
  44842. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44843. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44844. }
  44845. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44846. if (this._metallicTexture) {
  44847. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44848. }
  44849. else if (this._reflectivityTexture) {
  44850. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44851. }
  44852. if (this._microSurfaceTexture) {
  44853. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44854. }
  44855. }
  44856. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44857. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44858. }
  44859. }
  44860. // Clip plane
  44861. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44862. // Colors
  44863. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44864. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44865. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44866. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44867. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44868. }
  44869. if (mustRebind || !this.isFrozen) {
  44870. // Lights
  44871. if (scene.lightsEnabled && !this._disableLighting) {
  44872. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44873. }
  44874. // View
  44875. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44876. this.bindView(effect);
  44877. }
  44878. // Fog
  44879. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  44880. // Morph targets
  44881. if (defines.NUM_MORPH_INFLUENCERS) {
  44882. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44883. }
  44884. // image processing
  44885. this._imageProcessingConfiguration.bind(this._activeEffect);
  44886. // Log. depth
  44887. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44888. }
  44889. this._uniformBuffer.update();
  44890. this._afterBind(mesh, this._activeEffect);
  44891. };
  44892. /**
  44893. * Returns the animatable textures.
  44894. * @returns - Array of animatable textures.
  44895. */
  44896. PBRBaseMaterial.prototype.getAnimatables = function () {
  44897. var results = [];
  44898. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44899. results.push(this._albedoTexture);
  44900. }
  44901. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44902. results.push(this._ambientTexture);
  44903. }
  44904. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44905. results.push(this._opacityTexture);
  44906. }
  44907. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44908. results.push(this._reflectionTexture);
  44909. }
  44910. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44911. results.push(this._emissiveTexture);
  44912. }
  44913. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44914. results.push(this._metallicTexture);
  44915. }
  44916. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44917. results.push(this._reflectivityTexture);
  44918. }
  44919. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44920. results.push(this._bumpTexture);
  44921. }
  44922. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44923. results.push(this._lightmapTexture);
  44924. }
  44925. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44926. results.push(this._refractionTexture);
  44927. }
  44928. return results;
  44929. };
  44930. /**
  44931. * Returns the texture used for reflections.
  44932. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44933. */
  44934. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44935. if (this._reflectionTexture) {
  44936. return this._reflectionTexture;
  44937. }
  44938. return this.getScene().environmentTexture;
  44939. };
  44940. /**
  44941. * Returns the texture used for refraction or null if none is used.
  44942. * @returns - Refection texture if present. If no refraction texture and refraction
  44943. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44944. */
  44945. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44946. if (this._refractionTexture) {
  44947. return this._refractionTexture;
  44948. }
  44949. if (this._linkRefractionWithTransparency) {
  44950. return this.getScene().environmentTexture;
  44951. }
  44952. return null;
  44953. };
  44954. /**
  44955. * Disposes the resources of the material.
  44956. * @param forceDisposeEffect - Forces the disposal of effects.
  44957. * @param forceDisposeTextures - Forces the disposal of all textures.
  44958. */
  44959. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44960. if (forceDisposeTextures) {
  44961. if (this._albedoTexture) {
  44962. this._albedoTexture.dispose();
  44963. }
  44964. if (this._ambientTexture) {
  44965. this._ambientTexture.dispose();
  44966. }
  44967. if (this._opacityTexture) {
  44968. this._opacityTexture.dispose();
  44969. }
  44970. if (this._reflectionTexture) {
  44971. this._reflectionTexture.dispose();
  44972. }
  44973. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44974. this._environmentBRDFTexture.dispose();
  44975. }
  44976. if (this._emissiveTexture) {
  44977. this._emissiveTexture.dispose();
  44978. }
  44979. if (this._metallicTexture) {
  44980. this._metallicTexture.dispose();
  44981. }
  44982. if (this._reflectivityTexture) {
  44983. this._reflectivityTexture.dispose();
  44984. }
  44985. if (this._bumpTexture) {
  44986. this._bumpTexture.dispose();
  44987. }
  44988. if (this._lightmapTexture) {
  44989. this._lightmapTexture.dispose();
  44990. }
  44991. if (this._refractionTexture) {
  44992. this._refractionTexture.dispose();
  44993. }
  44994. }
  44995. this._renderTargets.dispose();
  44996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44998. }
  44999. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45000. };
  45001. /**
  45002. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45003. */
  45004. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45005. /**
  45006. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45007. * to enhance interoperability with other engines.
  45008. */
  45009. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45010. /**
  45011. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45012. * to enhance interoperability with other materials.
  45013. */
  45014. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45015. /**
  45016. * Stores the reflectivity values based on metallic roughness workflow.
  45017. */
  45018. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45019. __decorate([
  45020. BABYLON.serializeAsImageProcessingConfiguration()
  45021. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45022. __decorate([
  45023. BABYLON.serialize()
  45024. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45025. __decorate([
  45026. BABYLON.serialize()
  45027. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45028. return PBRBaseMaterial;
  45029. }(BABYLON.PushMaterial));
  45030. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45031. })(BABYLON || (BABYLON = {}));
  45032. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45033. var BABYLON;
  45034. (function (BABYLON) {
  45035. /**
  45036. * The Physically based simple base material of BJS.
  45037. *
  45038. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45039. * It is used as the base class for both the specGloss and metalRough conventions.
  45040. */
  45041. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45042. __extends(PBRBaseSimpleMaterial, _super);
  45043. /**
  45044. * Instantiates a new PBRMaterial instance.
  45045. *
  45046. * @param name The material name
  45047. * @param scene The scene the material will be use in.
  45048. */
  45049. function PBRBaseSimpleMaterial(name, scene) {
  45050. var _this = _super.call(this, name, scene) || this;
  45051. /**
  45052. * Number of Simultaneous lights allowed on the material.
  45053. */
  45054. _this.maxSimultaneousLights = 4;
  45055. /**
  45056. * If sets to true, disables all the lights affecting the material.
  45057. */
  45058. _this.disableLighting = false;
  45059. /**
  45060. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45061. */
  45062. _this.invertNormalMapX = false;
  45063. /**
  45064. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45065. */
  45066. _this.invertNormalMapY = false;
  45067. /**
  45068. * Emissivie color used to self-illuminate the model.
  45069. */
  45070. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45071. /**
  45072. * Occlusion Channel Strenght.
  45073. */
  45074. _this.occlusionStrength = 1.0;
  45075. _this.useLightmapAsShadowmap = false;
  45076. _this._useAlphaFromAlbedoTexture = true;
  45077. _this._useAmbientInGrayScale = true;
  45078. return _this;
  45079. }
  45080. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45081. /**
  45082. * Gets the current double sided mode.
  45083. */
  45084. get: function () {
  45085. return this._twoSidedLighting;
  45086. },
  45087. /**
  45088. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45089. */
  45090. set: function (value) {
  45091. if (this._twoSidedLighting === value) {
  45092. return;
  45093. }
  45094. this._twoSidedLighting = value;
  45095. this.backFaceCulling = !value;
  45096. this._markAllSubMeshesAsTexturesDirty();
  45097. },
  45098. enumerable: true,
  45099. configurable: true
  45100. });
  45101. /**
  45102. * Return the active textures of the material.
  45103. */
  45104. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45105. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45106. if (this.environmentTexture) {
  45107. activeTextures.push(this.environmentTexture);
  45108. }
  45109. if (this.normalTexture) {
  45110. activeTextures.push(this.normalTexture);
  45111. }
  45112. if (this.emissiveTexture) {
  45113. activeTextures.push(this.emissiveTexture);
  45114. }
  45115. if (this.occlusionTexture) {
  45116. activeTextures.push(this.occlusionTexture);
  45117. }
  45118. if (this.lightmapTexture) {
  45119. activeTextures.push(this.lightmapTexture);
  45120. }
  45121. return activeTextures;
  45122. };
  45123. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45124. if (_super.prototype.hasTexture.call(this, texture)) {
  45125. return true;
  45126. }
  45127. if (this.lightmapTexture === texture) {
  45128. return true;
  45129. }
  45130. return false;
  45131. };
  45132. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45133. return "PBRBaseSimpleMaterial";
  45134. };
  45135. __decorate([
  45136. BABYLON.serialize(),
  45137. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45138. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45139. __decorate([
  45140. BABYLON.serialize(),
  45141. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45142. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45143. __decorate([
  45144. BABYLON.serializeAsTexture(),
  45145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45146. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45147. __decorate([
  45148. BABYLON.serialize(),
  45149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45150. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45151. __decorate([
  45152. BABYLON.serialize(),
  45153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45154. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45155. __decorate([
  45156. BABYLON.serializeAsTexture(),
  45157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45158. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45159. __decorate([
  45160. BABYLON.serializeAsColor3("emissive"),
  45161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45162. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45163. __decorate([
  45164. BABYLON.serializeAsTexture(),
  45165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45166. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45167. __decorate([
  45168. BABYLON.serialize(),
  45169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45170. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45171. __decorate([
  45172. BABYLON.serializeAsTexture(),
  45173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45174. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45175. __decorate([
  45176. BABYLON.serialize(),
  45177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45178. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45179. __decorate([
  45180. BABYLON.serialize()
  45181. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45182. __decorate([
  45183. BABYLON.serializeAsTexture(),
  45184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45185. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45186. __decorate([
  45187. BABYLON.serialize(),
  45188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45189. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45190. return PBRBaseSimpleMaterial;
  45191. }(BABYLON.PBRBaseMaterial));
  45192. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45193. })(BABYLON || (BABYLON = {}));
  45194. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45195. var BABYLON;
  45196. (function (BABYLON) {
  45197. /**
  45198. * The Physically based material of BJS.
  45199. *
  45200. * This offers the main features of a standard PBR material.
  45201. * For more information, please refer to the documentation :
  45202. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45203. */
  45204. var PBRMaterial = /** @class */ (function (_super) {
  45205. __extends(PBRMaterial, _super);
  45206. /**
  45207. * Instantiates a new PBRMaterial instance.
  45208. *
  45209. * @param name The material name
  45210. * @param scene The scene the material will be use in.
  45211. */
  45212. function PBRMaterial(name, scene) {
  45213. var _this = _super.call(this, name, scene) || this;
  45214. /**
  45215. * Intensity of the direct lights e.g. the four lights available in your scene.
  45216. * This impacts both the direct diffuse and specular highlights.
  45217. */
  45218. _this.directIntensity = 1.0;
  45219. /**
  45220. * Intensity of the emissive part of the material.
  45221. * This helps controlling the emissive effect without modifying the emissive color.
  45222. */
  45223. _this.emissiveIntensity = 1.0;
  45224. /**
  45225. * Intensity of the environment e.g. how much the environment will light the object
  45226. * either through harmonics for rough material or through the refelction for shiny ones.
  45227. */
  45228. _this.environmentIntensity = 1.0;
  45229. /**
  45230. * This is a special control allowing the reduction of the specular highlights coming from the
  45231. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45232. */
  45233. _this.specularIntensity = 1.0;
  45234. /**
  45235. * Debug Control allowing disabling the bump map on this material.
  45236. */
  45237. _this.disableBumpMap = false;
  45238. /**
  45239. * AKA Occlusion Texture Intensity in other nomenclature.
  45240. */
  45241. _this.ambientTextureStrength = 1.0;
  45242. /**
  45243. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45244. * 1 means it completely occludes it
  45245. * 0 mean it has no impact
  45246. */
  45247. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45248. /**
  45249. * The color of a material in ambient lighting.
  45250. */
  45251. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45252. /**
  45253. * AKA Diffuse Color in other nomenclature.
  45254. */
  45255. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45256. /**
  45257. * AKA Specular Color in other nomenclature.
  45258. */
  45259. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45260. /**
  45261. * The color reflected from the material.
  45262. */
  45263. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45264. /**
  45265. * The color emitted from the material.
  45266. */
  45267. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45268. /**
  45269. * AKA Glossiness in other nomenclature.
  45270. */
  45271. _this.microSurface = 1.0;
  45272. /**
  45273. * source material index of refraction (IOR)' / 'destination material IOR.
  45274. */
  45275. _this.indexOfRefraction = 0.66;
  45276. /**
  45277. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45278. */
  45279. _this.invertRefractionY = false;
  45280. /**
  45281. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45282. * Materials half opaque for instance using refraction could benefit from this control.
  45283. */
  45284. _this.linkRefractionWithTransparency = false;
  45285. _this.useLightmapAsShadowmap = false;
  45286. /**
  45287. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45288. */
  45289. _this.useAlphaFromAlbedoTexture = false;
  45290. /**
  45291. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45292. */
  45293. _this.forceAlphaTest = false;
  45294. /**
  45295. * Defines the alpha limits in alpha test mode.
  45296. */
  45297. _this.alphaCutOff = 0.4;
  45298. /**
  45299. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45300. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45301. */
  45302. _this.useSpecularOverAlpha = true;
  45303. /**
  45304. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45305. */
  45306. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45307. /**
  45308. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45309. */
  45310. _this.useRoughnessFromMetallicTextureAlpha = true;
  45311. /**
  45312. * Specifies if the metallic texture contains the roughness information in its green channel.
  45313. */
  45314. _this.useRoughnessFromMetallicTextureGreen = false;
  45315. /**
  45316. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45317. */
  45318. _this.useMetallnessFromMetallicTextureBlue = false;
  45319. /**
  45320. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45321. */
  45322. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45323. /**
  45324. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45325. */
  45326. _this.useAmbientInGrayScale = false;
  45327. /**
  45328. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45329. * The material will try to infer what glossiness each pixel should be.
  45330. */
  45331. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45332. /**
  45333. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45334. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45335. */
  45336. _this.useRadianceOverAlpha = true;
  45337. /**
  45338. * Allows using an object space normal map (instead of tangent space).
  45339. */
  45340. _this.useObjectSpaceNormalMap = false;
  45341. /**
  45342. * Allows using the bump map in parallax mode.
  45343. */
  45344. _this.useParallax = false;
  45345. /**
  45346. * Allows using the bump map in parallax occlusion mode.
  45347. */
  45348. _this.useParallaxOcclusion = false;
  45349. /**
  45350. * Controls the scale bias of the parallax mode.
  45351. */
  45352. _this.parallaxScaleBias = 0.05;
  45353. /**
  45354. * If sets to true, disables all the lights affecting the material.
  45355. */
  45356. _this.disableLighting = false;
  45357. /**
  45358. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45359. */
  45360. _this.forceIrradianceInFragment = false;
  45361. /**
  45362. * Number of Simultaneous lights allowed on the material.
  45363. */
  45364. _this.maxSimultaneousLights = 4;
  45365. /**
  45366. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45367. */
  45368. _this.invertNormalMapX = false;
  45369. /**
  45370. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45371. */
  45372. _this.invertNormalMapY = false;
  45373. /**
  45374. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45375. */
  45376. _this.twoSidedLighting = false;
  45377. /**
  45378. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45379. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45380. */
  45381. _this.useAlphaFresnel = false;
  45382. /**
  45383. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45384. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45385. */
  45386. _this.useLinearAlphaFresnel = false;
  45387. /**
  45388. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45389. * And/Or occlude the blended part.
  45390. */
  45391. _this.environmentBRDFTexture = null;
  45392. /**
  45393. * Force normal to face away from face.
  45394. */
  45395. _this.forceNormalForward = false;
  45396. /**
  45397. * Enables specular anti aliasing in the PBR shader.
  45398. * It will both interacts on the Geometry for analytical and IBL lighting.
  45399. * It also prefilter the roughness map based on the bump values.
  45400. */
  45401. _this.enableSpecularAntiAliasing = false;
  45402. /**
  45403. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45404. * makes the reflect vector face the model (under horizon).
  45405. */
  45406. _this.useHorizonOcclusion = true;
  45407. /**
  45408. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45409. * too much the area relying on ambient texture to define their ambient occlusion.
  45410. */
  45411. _this.useRadianceOcclusion = true;
  45412. /**
  45413. * If set to true, no lighting calculations will be applied.
  45414. */
  45415. _this.unlit = false;
  45416. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45417. return _this;
  45418. }
  45419. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45420. /**
  45421. * BJS is using an harcoded light falloff based on a manually sets up range.
  45422. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45423. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45424. */
  45425. get: function () {
  45426. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45427. },
  45428. /**
  45429. * BJS is using an harcoded light falloff based on a manually sets up range.
  45430. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45431. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45432. */
  45433. set: function (value) {
  45434. if (value !== this.usePhysicalLightFalloff) {
  45435. // Ensure the effect will be rebuilt.
  45436. this._markAllSubMeshesAsTexturesDirty();
  45437. if (value) {
  45438. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45439. }
  45440. else {
  45441. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45442. }
  45443. }
  45444. },
  45445. enumerable: true,
  45446. configurable: true
  45447. });
  45448. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45449. /**
  45450. * In order to support the falloff compatibility with gltf, a special mode has been added
  45451. * to reproduce the gltf light falloff.
  45452. */
  45453. get: function () {
  45454. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45455. },
  45456. /**
  45457. * In order to support the falloff compatibility with gltf, a special mode has been added
  45458. * to reproduce the gltf light falloff.
  45459. */
  45460. set: function (value) {
  45461. if (value !== this.useGLTFLightFalloff) {
  45462. // Ensure the effect will be rebuilt.
  45463. this._markAllSubMeshesAsTexturesDirty();
  45464. if (value) {
  45465. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45466. }
  45467. else {
  45468. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45469. }
  45470. }
  45471. },
  45472. enumerable: true,
  45473. configurable: true
  45474. });
  45475. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45476. /**
  45477. * Gets the image processing configuration used either in this material.
  45478. */
  45479. get: function () {
  45480. return this._imageProcessingConfiguration;
  45481. },
  45482. /**
  45483. * Sets the Default image processing configuration used either in the this material.
  45484. *
  45485. * If sets to null, the scene one is in use.
  45486. */
  45487. set: function (value) {
  45488. this._attachImageProcessingConfiguration(value);
  45489. // Ensure the effect will be rebuilt.
  45490. this._markAllSubMeshesAsTexturesDirty();
  45491. },
  45492. enumerable: true,
  45493. configurable: true
  45494. });
  45495. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45496. /**
  45497. * Gets wether the color curves effect is enabled.
  45498. */
  45499. get: function () {
  45500. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45501. },
  45502. /**
  45503. * Sets wether the color curves effect is enabled.
  45504. */
  45505. set: function (value) {
  45506. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45507. },
  45508. enumerable: true,
  45509. configurable: true
  45510. });
  45511. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45512. /**
  45513. * Gets wether the color grading effect is enabled.
  45514. */
  45515. get: function () {
  45516. return this.imageProcessingConfiguration.colorGradingEnabled;
  45517. },
  45518. /**
  45519. * Gets wether the color grading effect is enabled.
  45520. */
  45521. set: function (value) {
  45522. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45523. },
  45524. enumerable: true,
  45525. configurable: true
  45526. });
  45527. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45528. /**
  45529. * Gets wether tonemapping is enabled or not.
  45530. */
  45531. get: function () {
  45532. return this._imageProcessingConfiguration.toneMappingEnabled;
  45533. },
  45534. /**
  45535. * Sets wether tonemapping is enabled or not
  45536. */
  45537. set: function (value) {
  45538. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45539. },
  45540. enumerable: true,
  45541. configurable: true
  45542. });
  45543. ;
  45544. ;
  45545. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45546. /**
  45547. * The camera exposure used on this material.
  45548. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45549. * This corresponds to a photographic exposure.
  45550. */
  45551. get: function () {
  45552. return this._imageProcessingConfiguration.exposure;
  45553. },
  45554. /**
  45555. * The camera exposure used on this material.
  45556. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45557. * This corresponds to a photographic exposure.
  45558. */
  45559. set: function (value) {
  45560. this._imageProcessingConfiguration.exposure = value;
  45561. },
  45562. enumerable: true,
  45563. configurable: true
  45564. });
  45565. ;
  45566. ;
  45567. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45568. /**
  45569. * Gets The camera contrast used on this material.
  45570. */
  45571. get: function () {
  45572. return this._imageProcessingConfiguration.contrast;
  45573. },
  45574. /**
  45575. * Sets The camera contrast used on this material.
  45576. */
  45577. set: function (value) {
  45578. this._imageProcessingConfiguration.contrast = value;
  45579. },
  45580. enumerable: true,
  45581. configurable: true
  45582. });
  45583. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45584. /**
  45585. * Gets the Color Grading 2D Lookup Texture.
  45586. */
  45587. get: function () {
  45588. return this._imageProcessingConfiguration.colorGradingTexture;
  45589. },
  45590. /**
  45591. * Sets the Color Grading 2D Lookup Texture.
  45592. */
  45593. set: function (value) {
  45594. this._imageProcessingConfiguration.colorGradingTexture = value;
  45595. },
  45596. enumerable: true,
  45597. configurable: true
  45598. });
  45599. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45600. /**
  45601. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45602. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45603. * 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;
  45604. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45605. */
  45606. get: function () {
  45607. return this._imageProcessingConfiguration.colorCurves;
  45608. },
  45609. /**
  45610. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45611. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45612. * 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;
  45613. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45614. */
  45615. set: function (value) {
  45616. this._imageProcessingConfiguration.colorCurves = value;
  45617. },
  45618. enumerable: true,
  45619. configurable: true
  45620. });
  45621. /**
  45622. * Returns the name of this material class.
  45623. */
  45624. PBRMaterial.prototype.getClassName = function () {
  45625. return "PBRMaterial";
  45626. };
  45627. /**
  45628. * Returns an array of the actively used textures.
  45629. * @returns - Array of BaseTextures
  45630. */
  45631. PBRMaterial.prototype.getActiveTextures = function () {
  45632. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45633. if (this._albedoTexture) {
  45634. activeTextures.push(this._albedoTexture);
  45635. }
  45636. if (this._ambientTexture) {
  45637. activeTextures.push(this._ambientTexture);
  45638. }
  45639. if (this._opacityTexture) {
  45640. activeTextures.push(this._opacityTexture);
  45641. }
  45642. if (this._reflectionTexture) {
  45643. activeTextures.push(this._reflectionTexture);
  45644. }
  45645. if (this._emissiveTexture) {
  45646. activeTextures.push(this._emissiveTexture);
  45647. }
  45648. if (this._reflectivityTexture) {
  45649. activeTextures.push(this._reflectivityTexture);
  45650. }
  45651. if (this._metallicTexture) {
  45652. activeTextures.push(this._metallicTexture);
  45653. }
  45654. if (this._microSurfaceTexture) {
  45655. activeTextures.push(this._microSurfaceTexture);
  45656. }
  45657. if (this._bumpTexture) {
  45658. activeTextures.push(this._bumpTexture);
  45659. }
  45660. if (this._lightmapTexture) {
  45661. activeTextures.push(this._lightmapTexture);
  45662. }
  45663. if (this._refractionTexture) {
  45664. activeTextures.push(this._refractionTexture);
  45665. }
  45666. return activeTextures;
  45667. };
  45668. /**
  45669. * Checks to see if a texture is used in the material.
  45670. * @param texture - Base texture to use.
  45671. * @returns - Boolean specifying if a texture is used in the material.
  45672. */
  45673. PBRMaterial.prototype.hasTexture = function (texture) {
  45674. if (_super.prototype.hasTexture.call(this, texture)) {
  45675. return true;
  45676. }
  45677. if (this._albedoTexture === texture) {
  45678. return true;
  45679. }
  45680. if (this._ambientTexture === texture) {
  45681. return true;
  45682. }
  45683. if (this._opacityTexture === texture) {
  45684. return true;
  45685. }
  45686. if (this._reflectionTexture === texture) {
  45687. return true;
  45688. }
  45689. if (this._reflectivityTexture === texture) {
  45690. return true;
  45691. }
  45692. if (this._metallicTexture === texture) {
  45693. return true;
  45694. }
  45695. if (this._microSurfaceTexture === texture) {
  45696. return true;
  45697. }
  45698. if (this._bumpTexture === texture) {
  45699. return true;
  45700. }
  45701. if (this._lightmapTexture === texture) {
  45702. return true;
  45703. }
  45704. if (this._refractionTexture === texture) {
  45705. return true;
  45706. }
  45707. return false;
  45708. };
  45709. /**
  45710. * Makes a duplicate of the current material.
  45711. * @param name - name to use for the new material.
  45712. */
  45713. PBRMaterial.prototype.clone = function (name) {
  45714. var _this = this;
  45715. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45716. clone.id = name;
  45717. clone.name = name;
  45718. return clone;
  45719. };
  45720. /**
  45721. * Serializes this PBR Material.
  45722. * @returns - An object with the serialized material.
  45723. */
  45724. PBRMaterial.prototype.serialize = function () {
  45725. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45726. serializationObject.customType = "BABYLON.PBRMaterial";
  45727. return serializationObject;
  45728. };
  45729. // Statics
  45730. /**
  45731. * Parses a PBR Material from a serialized object.
  45732. * @param source - Serialized object.
  45733. * @param scene - BJS scene instance.
  45734. * @param rootUrl - url for the scene object
  45735. * @returns - PBRMaterial
  45736. */
  45737. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45738. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45739. };
  45740. /**
  45741. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45742. */
  45743. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45744. /**
  45745. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45746. */
  45747. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45748. /**
  45749. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45750. */
  45751. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45752. /**
  45753. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45754. * They are also discarded below the alpha cutoff threshold to improve performances.
  45755. */
  45756. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45757. /**
  45758. * Defines the default value of how much AO map is occluding the analytical lights
  45759. * (point spot...).
  45760. */
  45761. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMaterial.prototype, "directIntensity", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45773. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45774. __decorate([
  45775. BABYLON.serialize(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45777. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45778. __decorate([
  45779. BABYLON.serialize(),
  45780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45781. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45782. __decorate([
  45783. BABYLON.serializeAsTexture(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45785. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45786. __decorate([
  45787. BABYLON.serializeAsTexture(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45789. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45790. __decorate([
  45791. BABYLON.serialize(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45798. __decorate([
  45799. BABYLON.serializeAsTexture(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45801. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45802. __decorate([
  45803. BABYLON.serializeAsTexture(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45806. __decorate([
  45807. BABYLON.serializeAsTexture(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45809. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45810. __decorate([
  45811. BABYLON.serializeAsTexture(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45814. __decorate([
  45815. BABYLON.serializeAsTexture(),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45818. __decorate([
  45819. BABYLON.serialize(),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45821. ], PBRMaterial.prototype, "metallic", void 0);
  45822. __decorate([
  45823. BABYLON.serialize(),
  45824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45825. ], PBRMaterial.prototype, "roughness", void 0);
  45826. __decorate([
  45827. BABYLON.serializeAsTexture(),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45829. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45830. __decorate([
  45831. BABYLON.serializeAsTexture(),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45834. __decorate([
  45835. BABYLON.serializeAsTexture(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45837. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45838. __decorate([
  45839. BABYLON.serializeAsTexture(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45841. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45842. __decorate([
  45843. BABYLON.serializeAsColor3("ambient"),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "ambientColor", void 0);
  45846. __decorate([
  45847. BABYLON.serializeAsColor3("albedo"),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "albedoColor", void 0);
  45850. __decorate([
  45851. BABYLON.serializeAsColor3("reflectivity"),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45854. __decorate([
  45855. BABYLON.serializeAsColor3("reflection"),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45857. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45858. __decorate([
  45859. BABYLON.serializeAsColor3("emissive"),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45861. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45865. ], PBRMaterial.prototype, "microSurface", void 0);
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45873. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45878. __decorate([
  45879. BABYLON.serialize(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45885. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45889. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45890. __decorate([
  45891. BABYLON.serialize(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45893. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45894. __decorate([
  45895. BABYLON.serialize(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45898. __decorate([
  45899. BABYLON.serialize(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45902. __decorate([
  45903. BABYLON.serialize(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45906. __decorate([
  45907. BABYLON.serialize(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45909. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45910. __decorate([
  45911. BABYLON.serialize(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45914. __decorate([
  45915. BABYLON.serialize(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45918. __decorate([
  45919. BABYLON.serialize(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45922. __decorate([
  45923. BABYLON.serialize(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45926. __decorate([
  45927. BABYLON.serialize()
  45928. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45929. __decorate([
  45930. BABYLON.serialize()
  45931. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45932. __decorate([
  45933. BABYLON.serialize(),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45935. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45936. __decorate([
  45937. BABYLON.serialize(),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45939. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45940. __decorate([
  45941. BABYLON.serialize(),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45943. ], PBRMaterial.prototype, "useParallax", void 0);
  45944. __decorate([
  45945. BABYLON.serialize(),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45947. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45948. __decorate([
  45949. BABYLON.serialize(),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45951. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45952. __decorate([
  45953. BABYLON.serialize(),
  45954. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45955. ], PBRMaterial.prototype, "disableLighting", void 0);
  45956. __decorate([
  45957. BABYLON.serialize(),
  45958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45959. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45960. __decorate([
  45961. BABYLON.serialize(),
  45962. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45963. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45964. __decorate([
  45965. BABYLON.serialize(),
  45966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45967. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45968. __decorate([
  45969. BABYLON.serialize(),
  45970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45971. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45972. __decorate([
  45973. BABYLON.serialize(),
  45974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45975. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45976. __decorate([
  45977. BABYLON.serialize(),
  45978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45979. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45980. __decorate([
  45981. BABYLON.serialize(),
  45982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45983. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45984. __decorate([
  45985. BABYLON.serializeAsTexture(),
  45986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45987. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45988. __decorate([
  45989. BABYLON.serialize(),
  45990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45991. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45992. __decorate([
  45993. BABYLON.serialize(),
  45994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45995. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45996. __decorate([
  45997. BABYLON.serialize(),
  45998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45999. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46000. __decorate([
  46001. BABYLON.serialize(),
  46002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46003. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46004. __decorate([
  46005. BABYLON.serialize(),
  46006. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46007. ], PBRMaterial.prototype, "unlit", void 0);
  46008. return PBRMaterial;
  46009. }(BABYLON.PBRBaseMaterial));
  46010. BABYLON.PBRMaterial = PBRMaterial;
  46011. })(BABYLON || (BABYLON = {}));
  46012. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46013. var BABYLON;
  46014. (function (BABYLON) {
  46015. /**
  46016. * The PBR material of BJS following the metal roughness convention.
  46017. *
  46018. * This fits to the PBR convention in the GLTF definition:
  46019. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46020. */
  46021. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46022. __extends(PBRMetallicRoughnessMaterial, _super);
  46023. /**
  46024. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46025. *
  46026. * @param name The material name
  46027. * @param scene The scene the material will be use in.
  46028. */
  46029. function PBRMetallicRoughnessMaterial(name, scene) {
  46030. var _this = _super.call(this, name, scene) || this;
  46031. _this._useRoughnessFromMetallicTextureAlpha = false;
  46032. _this._useRoughnessFromMetallicTextureGreen = true;
  46033. _this._useMetallnessFromMetallicTextureBlue = true;
  46034. _this.metallic = 1.0;
  46035. _this.roughness = 1.0;
  46036. return _this;
  46037. }
  46038. /**
  46039. * Return the currrent class name of the material.
  46040. */
  46041. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46042. return "PBRMetallicRoughnessMaterial";
  46043. };
  46044. /**
  46045. * Return the active textures of the material.
  46046. */
  46047. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46048. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46049. if (this.baseTexture) {
  46050. activeTextures.push(this.baseTexture);
  46051. }
  46052. if (this.metallicRoughnessTexture) {
  46053. activeTextures.push(this.metallicRoughnessTexture);
  46054. }
  46055. return activeTextures;
  46056. };
  46057. /**
  46058. * Checks to see if a texture is used in the material.
  46059. * @param texture - Base texture to use.
  46060. * @returns - Boolean specifying if a texture is used in the material.
  46061. */
  46062. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46063. if (_super.prototype.hasTexture.call(this, texture)) {
  46064. return true;
  46065. }
  46066. if (this.baseTexture === texture) {
  46067. return true;
  46068. }
  46069. if (this.metallicRoughnessTexture === texture) {
  46070. return true;
  46071. }
  46072. return false;
  46073. };
  46074. /**
  46075. * Makes a duplicate of the current material.
  46076. * @param name - name to use for the new material.
  46077. */
  46078. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46079. var _this = this;
  46080. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46081. clone.id = name;
  46082. clone.name = name;
  46083. return clone;
  46084. };
  46085. /**
  46086. * Serialize the material to a parsable JSON object.
  46087. */
  46088. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46089. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46090. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46091. return serializationObject;
  46092. };
  46093. /**
  46094. * Parses a JSON object correponding to the serialize function.
  46095. */
  46096. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46097. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46098. };
  46099. __decorate([
  46100. BABYLON.serializeAsColor3(),
  46101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46102. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46103. __decorate([
  46104. BABYLON.serializeAsTexture(),
  46105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46106. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46107. __decorate([
  46108. BABYLON.serialize(),
  46109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46110. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46111. __decorate([
  46112. BABYLON.serialize(),
  46113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46114. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46115. __decorate([
  46116. BABYLON.serializeAsTexture(),
  46117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46118. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46119. return PBRMetallicRoughnessMaterial;
  46120. }(BABYLON.PBRBaseSimpleMaterial));
  46121. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46122. })(BABYLON || (BABYLON = {}));
  46123. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46124. var BABYLON;
  46125. (function (BABYLON) {
  46126. /**
  46127. * The PBR material of BJS following the specular glossiness convention.
  46128. *
  46129. * This fits to the PBR convention in the GLTF definition:
  46130. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46131. */
  46132. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46133. __extends(PBRSpecularGlossinessMaterial, _super);
  46134. /**
  46135. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46136. *
  46137. * @param name The material name
  46138. * @param scene The scene the material will be use in.
  46139. */
  46140. function PBRSpecularGlossinessMaterial(name, scene) {
  46141. var _this = _super.call(this, name, scene) || this;
  46142. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46143. return _this;
  46144. }
  46145. /**
  46146. * Return the currrent class name of the material.
  46147. */
  46148. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46149. return "PBRSpecularGlossinessMaterial";
  46150. };
  46151. /**
  46152. * Return the active textures of the material.
  46153. */
  46154. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46155. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46156. if (this.diffuseTexture) {
  46157. activeTextures.push(this.diffuseTexture);
  46158. }
  46159. if (this.specularGlossinessTexture) {
  46160. activeTextures.push(this.specularGlossinessTexture);
  46161. }
  46162. return activeTextures;
  46163. };
  46164. /**
  46165. * Checks to see if a texture is used in the material.
  46166. * @param texture - Base texture to use.
  46167. * @returns - Boolean specifying if a texture is used in the material.
  46168. */
  46169. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46170. if (_super.prototype.hasTexture.call(this, texture)) {
  46171. return true;
  46172. }
  46173. if (this.diffuseTexture === texture) {
  46174. return true;
  46175. }
  46176. if (this.specularGlossinessTexture === texture) {
  46177. return true;
  46178. }
  46179. return false;
  46180. };
  46181. /**
  46182. * Makes a duplicate of the current material.
  46183. * @param name - name to use for the new material.
  46184. */
  46185. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46186. var _this = this;
  46187. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46188. clone.id = name;
  46189. clone.name = name;
  46190. return clone;
  46191. };
  46192. /**
  46193. * Serialize the material to a parsable JSON object.
  46194. */
  46195. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46196. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46197. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46198. return serializationObject;
  46199. };
  46200. /**
  46201. * Parses a JSON object correponding to the serialize function.
  46202. */
  46203. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46204. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46205. };
  46206. __decorate([
  46207. BABYLON.serializeAsColor3("diffuse"),
  46208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46209. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46210. __decorate([
  46211. BABYLON.serializeAsTexture(),
  46212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46213. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46214. __decorate([
  46215. BABYLON.serializeAsColor3("specular"),
  46216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46217. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46218. __decorate([
  46219. BABYLON.serialize(),
  46220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46221. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46222. __decorate([
  46223. BABYLON.serializeAsTexture(),
  46224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46225. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46226. return PBRSpecularGlossinessMaterial;
  46227. }(BABYLON.PBRBaseSimpleMaterial));
  46228. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46229. })(BABYLON || (BABYLON = {}));
  46230. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46231. var BABYLON;
  46232. (function (BABYLON) {
  46233. /**
  46234. * This is a list of all the different input types that are available in the application.
  46235. * Fo instance: ArcRotateCameraGamepadInput...
  46236. */
  46237. BABYLON.CameraInputTypes = {};
  46238. /**
  46239. * This represents the input manager used within a camera.
  46240. * It helps dealing with all the different kind of input attached to a camera.
  46241. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46242. */
  46243. var CameraInputsManager = /** @class */ (function () {
  46244. /**
  46245. * Instantiate a new Camera Input Manager.
  46246. * @param camera Defines the camera the input manager blongs to
  46247. */
  46248. function CameraInputsManager(camera) {
  46249. this.attached = {};
  46250. this.camera = camera;
  46251. this.checkInputs = function () { };
  46252. }
  46253. /**
  46254. * Add an input method to a camera
  46255. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46256. * @param input camera input method
  46257. */
  46258. CameraInputsManager.prototype.add = function (input) {
  46259. var type = input.getSimpleName();
  46260. if (this.attached[type]) {
  46261. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46262. return;
  46263. }
  46264. this.attached[type] = input;
  46265. input.camera = this.camera;
  46266. //for checkInputs, we are dynamically creating a function
  46267. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46268. if (input.checkInputs) {
  46269. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46270. }
  46271. if (this.attachedElement) {
  46272. input.attachControl(this.attachedElement);
  46273. }
  46274. };
  46275. /**
  46276. * Remove a specific input method from a camera
  46277. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46278. * @param inputToRemove camera input method
  46279. */
  46280. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46281. for (var cam in this.attached) {
  46282. var input = this.attached[cam];
  46283. if (input === inputToRemove) {
  46284. input.detachControl(this.attachedElement);
  46285. input.camera = null;
  46286. delete this.attached[cam];
  46287. this.rebuildInputCheck();
  46288. }
  46289. }
  46290. };
  46291. /**
  46292. * Remove a specific input type from a camera
  46293. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46294. * @param inputType the type of the input to remove
  46295. */
  46296. CameraInputsManager.prototype.removeByType = function (inputType) {
  46297. for (var cam in this.attached) {
  46298. var input = this.attached[cam];
  46299. if (input.getClassName() === inputType) {
  46300. input.detachControl(this.attachedElement);
  46301. input.camera = null;
  46302. delete this.attached[cam];
  46303. this.rebuildInputCheck();
  46304. }
  46305. }
  46306. };
  46307. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46308. var current = this.checkInputs;
  46309. return function () {
  46310. current();
  46311. fn();
  46312. };
  46313. };
  46314. /**
  46315. * Attach the input controls to the currently attached dom element to listen the events from.
  46316. * @param input Defines the input to attach
  46317. */
  46318. CameraInputsManager.prototype.attachInput = function (input) {
  46319. if (this.attachedElement) {
  46320. input.attachControl(this.attachedElement, this.noPreventDefault);
  46321. }
  46322. };
  46323. /**
  46324. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46325. * @param element Defines the dom element to collect the events from
  46326. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46327. */
  46328. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46329. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46330. if (this.attachedElement) {
  46331. return;
  46332. }
  46333. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46334. this.attachedElement = element;
  46335. this.noPreventDefault = noPreventDefault;
  46336. for (var cam in this.attached) {
  46337. this.attached[cam].attachControl(element, noPreventDefault);
  46338. }
  46339. };
  46340. /**
  46341. * Detach the current manager inputs controls from a specific dom element.
  46342. * @param element Defines the dom element to collect the events from
  46343. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46344. */
  46345. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46346. if (disconnect === void 0) { disconnect = false; }
  46347. if (this.attachedElement !== element) {
  46348. return;
  46349. }
  46350. for (var cam in this.attached) {
  46351. this.attached[cam].detachControl(element);
  46352. if (disconnect) {
  46353. this.attached[cam].camera = null;
  46354. }
  46355. }
  46356. this.attachedElement = null;
  46357. };
  46358. /**
  46359. * Rebuild the dynamic inputCheck function from the current list of
  46360. * defined inputs in the manager.
  46361. */
  46362. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46363. this.checkInputs = function () { };
  46364. for (var cam in this.attached) {
  46365. var input = this.attached[cam];
  46366. if (input.checkInputs) {
  46367. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46368. }
  46369. }
  46370. };
  46371. /**
  46372. * Remove all attached input methods from a camera
  46373. */
  46374. CameraInputsManager.prototype.clear = function () {
  46375. if (this.attachedElement) {
  46376. this.detachElement(this.attachedElement, true);
  46377. }
  46378. this.attached = {};
  46379. this.attachedElement = null;
  46380. this.checkInputs = function () { };
  46381. };
  46382. /**
  46383. * Serialize the current input manager attached to a camera.
  46384. * This ensures than once parsed,
  46385. * the input associated to the camera will be identical to the current ones
  46386. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46387. */
  46388. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46389. var inputs = {};
  46390. for (var cam in this.attached) {
  46391. var input = this.attached[cam];
  46392. var res = BABYLON.SerializationHelper.Serialize(input);
  46393. inputs[input.getClassName()] = res;
  46394. }
  46395. serializedCamera.inputsmgr = inputs;
  46396. };
  46397. /**
  46398. * Parses an input manager serialized JSON to restore the previous list of inputs
  46399. * and states associated to a camera.
  46400. * @param parsedCamera Defines the JSON to parse
  46401. */
  46402. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46403. var parsedInputs = parsedCamera.inputsmgr;
  46404. if (parsedInputs) {
  46405. this.clear();
  46406. for (var n in parsedInputs) {
  46407. var construct = BABYLON.CameraInputTypes[n];
  46408. if (construct) {
  46409. var parsedinput = parsedInputs[n];
  46410. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46411. this.add(input);
  46412. }
  46413. }
  46414. }
  46415. else {
  46416. //2016-03-08 this part is for managing backward compatibility
  46417. for (var n in this.attached) {
  46418. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46419. if (construct) {
  46420. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46421. this.remove(this.attached[n]);
  46422. this.add(input);
  46423. }
  46424. }
  46425. }
  46426. };
  46427. return CameraInputsManager;
  46428. }());
  46429. BABYLON.CameraInputsManager = CameraInputsManager;
  46430. })(BABYLON || (BABYLON = {}));
  46431. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46432. var BABYLON;
  46433. (function (BABYLON) {
  46434. /**
  46435. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46436. * This is the base of the follow, arc rotate cameras and Free camera
  46437. * @see http://doc.babylonjs.com/features/cameras
  46438. */
  46439. var TargetCamera = /** @class */ (function (_super) {
  46440. __extends(TargetCamera, _super);
  46441. /**
  46442. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46443. * This is the base of the follow, arc rotate cameras and Free camera
  46444. * @see http://doc.babylonjs.com/features/cameras
  46445. * @param name Defines the name of the camera in the scene
  46446. * @param position Defines the start position of the camera in the scene
  46447. * @param scene Defines the scene the camera belongs to
  46448. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46449. */
  46450. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46451. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46452. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46453. /**
  46454. * Define the current direction the camera is moving to
  46455. */
  46456. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46457. /**
  46458. * Define the current rotation the camera is rotating to
  46459. */
  46460. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46461. /**
  46462. * Define the current rotation of the camera
  46463. */
  46464. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46465. /**
  46466. * Define the current speed of the camera
  46467. */
  46468. _this.speed = 2.0;
  46469. /**
  46470. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46471. * around all axis.
  46472. */
  46473. _this.noRotationConstraint = false;
  46474. /**
  46475. * Define the current target of the camera as an object or a position.
  46476. */
  46477. _this.lockedTarget = null;
  46478. /** @hidden */
  46479. _this._currentTarget = BABYLON.Vector3.Zero();
  46480. /** @hidden */
  46481. _this._viewMatrix = BABYLON.Matrix.Zero();
  46482. /** @hidden */
  46483. _this._camMatrix = BABYLON.Matrix.Zero();
  46484. /** @hidden */
  46485. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46486. /** @hidden */
  46487. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46488. /** @hidden */
  46489. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46490. /** @hidden */
  46491. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46492. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46493. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46494. _this._defaultUp = BABYLON.Vector3.Up();
  46495. _this._cachedRotationZ = 0;
  46496. return _this;
  46497. }
  46498. /**
  46499. * Gets the position in front of the camera at a given distance.
  46500. * @param distance The distance from the camera we want the position to be
  46501. * @returns the position
  46502. */
  46503. TargetCamera.prototype.getFrontPosition = function (distance) {
  46504. this.getWorldMatrix();
  46505. var direction = this.getTarget().subtract(this.position);
  46506. direction.normalize();
  46507. direction.scaleInPlace(distance);
  46508. return this.globalPosition.add(direction);
  46509. };
  46510. /** @hidden */
  46511. TargetCamera.prototype._getLockedTargetPosition = function () {
  46512. if (!this.lockedTarget) {
  46513. return null;
  46514. }
  46515. if (this.lockedTarget.absolutePosition) {
  46516. this.lockedTarget.computeWorldMatrix();
  46517. }
  46518. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46519. };
  46520. /**
  46521. * Store current camera state of the camera (fov, position, rotation, etc..)
  46522. * @returns the camera
  46523. */
  46524. TargetCamera.prototype.storeState = function () {
  46525. this._storedPosition = this.position.clone();
  46526. this._storedRotation = this.rotation.clone();
  46527. if (this.rotationQuaternion) {
  46528. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46529. }
  46530. return _super.prototype.storeState.call(this);
  46531. };
  46532. /**
  46533. * Restored camera state. You must call storeState() first
  46534. * @returns whether it was successful or not
  46535. * @hidden
  46536. */
  46537. TargetCamera.prototype._restoreStateValues = function () {
  46538. if (!_super.prototype._restoreStateValues.call(this)) {
  46539. return false;
  46540. }
  46541. this.position = this._storedPosition.clone();
  46542. this.rotation = this._storedRotation.clone();
  46543. if (this.rotationQuaternion) {
  46544. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46545. }
  46546. this.cameraDirection.copyFromFloats(0, 0, 0);
  46547. this.cameraRotation.copyFromFloats(0, 0);
  46548. return true;
  46549. };
  46550. /** @hidden */
  46551. TargetCamera.prototype._initCache = function () {
  46552. _super.prototype._initCache.call(this);
  46553. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46554. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46555. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46556. };
  46557. /** @hidden */
  46558. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46559. if (!ignoreParentClass) {
  46560. _super.prototype._updateCache.call(this);
  46561. }
  46562. var lockedTargetPosition = this._getLockedTargetPosition();
  46563. if (!lockedTargetPosition) {
  46564. this._cache.lockedTarget = null;
  46565. }
  46566. else {
  46567. if (!this._cache.lockedTarget) {
  46568. this._cache.lockedTarget = lockedTargetPosition.clone();
  46569. }
  46570. else {
  46571. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46572. }
  46573. }
  46574. this._cache.rotation.copyFrom(this.rotation);
  46575. if (this.rotationQuaternion)
  46576. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46577. };
  46578. // Synchronized
  46579. /** @hidden */
  46580. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46581. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46582. return false;
  46583. }
  46584. var lockedTargetPosition = this._getLockedTargetPosition();
  46585. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46586. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46587. };
  46588. // Methods
  46589. /** @hidden */
  46590. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46591. var engine = this.getEngine();
  46592. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46593. };
  46594. // Target
  46595. /** @hidden */
  46596. TargetCamera.prototype.setTarget = function (target) {
  46597. this.upVector.normalize();
  46598. if (this.position.z === target.z) {
  46599. this.position.z += BABYLON.Epsilon;
  46600. }
  46601. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46602. this._camMatrix.invert();
  46603. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46604. var vDir = target.subtract(this.position);
  46605. if (vDir.x >= 0.0) {
  46606. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46607. }
  46608. else {
  46609. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46610. }
  46611. this.rotation.z = 0;
  46612. if (isNaN(this.rotation.x)) {
  46613. this.rotation.x = 0;
  46614. }
  46615. if (isNaN(this.rotation.y)) {
  46616. this.rotation.y = 0;
  46617. }
  46618. if (isNaN(this.rotation.z)) {
  46619. this.rotation.z = 0;
  46620. }
  46621. if (this.rotationQuaternion) {
  46622. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46623. }
  46624. };
  46625. /**
  46626. * Return the current target position of the camera. This value is expressed in local space.
  46627. * @returns the target position
  46628. */
  46629. TargetCamera.prototype.getTarget = function () {
  46630. return this._currentTarget;
  46631. };
  46632. /** @hidden */
  46633. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46634. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46635. };
  46636. /** @hidden */
  46637. TargetCamera.prototype._updatePosition = function () {
  46638. if (this.parent) {
  46639. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46640. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46641. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46642. return;
  46643. }
  46644. this.position.addInPlace(this.cameraDirection);
  46645. };
  46646. /** @hidden */
  46647. TargetCamera.prototype._checkInputs = function () {
  46648. var needToMove = this._decideIfNeedsToMove();
  46649. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46650. // Move
  46651. if (needToMove) {
  46652. this._updatePosition();
  46653. }
  46654. // Rotate
  46655. if (needToRotate) {
  46656. this.rotation.x += this.cameraRotation.x;
  46657. this.rotation.y += this.cameraRotation.y;
  46658. //rotate, if quaternion is set and rotation was used
  46659. if (this.rotationQuaternion) {
  46660. var len = this.rotation.lengthSquared();
  46661. if (len) {
  46662. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46663. }
  46664. }
  46665. if (!this.noRotationConstraint) {
  46666. var limit = (Math.PI / 2) * 0.95;
  46667. if (this.rotation.x > limit)
  46668. this.rotation.x = limit;
  46669. if (this.rotation.x < -limit)
  46670. this.rotation.x = -limit;
  46671. }
  46672. }
  46673. // Inertia
  46674. if (needToMove) {
  46675. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46676. this.cameraDirection.x = 0;
  46677. }
  46678. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46679. this.cameraDirection.y = 0;
  46680. }
  46681. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46682. this.cameraDirection.z = 0;
  46683. }
  46684. this.cameraDirection.scaleInPlace(this.inertia);
  46685. }
  46686. if (needToRotate) {
  46687. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46688. this.cameraRotation.x = 0;
  46689. }
  46690. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46691. this.cameraRotation.y = 0;
  46692. }
  46693. this.cameraRotation.scaleInPlace(this.inertia);
  46694. }
  46695. _super.prototype._checkInputs.call(this);
  46696. };
  46697. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46698. if (this.rotationQuaternion) {
  46699. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46700. }
  46701. else {
  46702. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46703. }
  46704. };
  46705. /**
  46706. * 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)
  46707. * @returns the current camera
  46708. */
  46709. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46710. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46711. return this;
  46712. };
  46713. /** @hidden */
  46714. TargetCamera.prototype._getViewMatrix = function () {
  46715. if (this.lockedTarget) {
  46716. this.setTarget(this._getLockedTargetPosition());
  46717. }
  46718. // Compute
  46719. this._updateCameraRotationMatrix();
  46720. // Apply the changed rotation to the upVector.
  46721. if (this._cachedRotationZ != this.rotation.z) {
  46722. this._rotateUpVectorWithCameraRotationMatrix();
  46723. this._cachedRotationZ = this.rotation.z;
  46724. }
  46725. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46726. // Computing target and final matrix
  46727. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46728. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46729. return this._viewMatrix;
  46730. };
  46731. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46732. if (this.parent) {
  46733. var parentWorldMatrix = this.parent.getWorldMatrix();
  46734. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46735. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46736. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46737. this._markSyncedWithParent();
  46738. }
  46739. else {
  46740. this._globalPosition.copyFrom(position);
  46741. this._globalCurrentTarget.copyFrom(target);
  46742. this._globalCurrentUpVector.copyFrom(up);
  46743. }
  46744. if (this.getScene().useRightHandedSystem) {
  46745. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46746. }
  46747. else {
  46748. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46749. }
  46750. };
  46751. /**
  46752. * @hidden
  46753. */
  46754. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46755. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46756. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46757. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46758. if (!this.rotationQuaternion) {
  46759. this.rotationQuaternion = new BABYLON.Quaternion();
  46760. }
  46761. rigCamera._cameraRigParams = {};
  46762. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46763. }
  46764. return rigCamera;
  46765. }
  46766. return null;
  46767. };
  46768. /**
  46769. * @hidden
  46770. */
  46771. TargetCamera.prototype._updateRigCameras = function () {
  46772. var camLeft = this._rigCameras[0];
  46773. var camRight = this._rigCameras[1];
  46774. switch (this.cameraRigMode) {
  46775. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46776. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46777. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46778. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46779. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46780. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46781. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46782. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46783. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46784. camLeft.setTarget(this.getTarget());
  46785. camRight.setTarget(this.getTarget());
  46786. break;
  46787. case BABYLON.Camera.RIG_MODE_VR:
  46788. if (camLeft.rotationQuaternion) {
  46789. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46790. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46791. }
  46792. else {
  46793. camLeft.rotation.copyFrom(this.rotation);
  46794. camRight.rotation.copyFrom(this.rotation);
  46795. }
  46796. camLeft.position.copyFrom(this.position);
  46797. camRight.position.copyFrom(this.position);
  46798. break;
  46799. }
  46800. _super.prototype._updateRigCameras.call(this);
  46801. };
  46802. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46803. if (!this._rigCamTransformMatrix) {
  46804. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46805. }
  46806. var target = this.getTarget();
  46807. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46808. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46809. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46810. };
  46811. /**
  46812. * Gets the current object class name.
  46813. * @return the class name
  46814. */
  46815. TargetCamera.prototype.getClassName = function () {
  46816. return "TargetCamera";
  46817. };
  46818. __decorate([
  46819. BABYLON.serializeAsVector3()
  46820. ], TargetCamera.prototype, "rotation", void 0);
  46821. __decorate([
  46822. BABYLON.serialize()
  46823. ], TargetCamera.prototype, "speed", void 0);
  46824. __decorate([
  46825. BABYLON.serializeAsMeshReference("lockedTargetId")
  46826. ], TargetCamera.prototype, "lockedTarget", void 0);
  46827. return TargetCamera;
  46828. }(BABYLON.Camera));
  46829. BABYLON.TargetCamera = TargetCamera;
  46830. })(BABYLON || (BABYLON = {}));
  46831. //# sourceMappingURL=babylon.targetCamera.js.map
  46832. var BABYLON;
  46833. (function (BABYLON) {
  46834. /**
  46835. * Manage the mouse inputs to control the movement of a free camera.
  46836. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46837. */
  46838. var FreeCameraMouseInput = /** @class */ (function () {
  46839. /**
  46840. * Manage the mouse inputs to control the movement of a free camera.
  46841. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46842. * @param touchEnabled Defines if touch is enabled or not
  46843. */
  46844. function FreeCameraMouseInput(
  46845. /**
  46846. * Define if touch is enabled in the mouse input
  46847. */
  46848. touchEnabled) {
  46849. if (touchEnabled === void 0) { touchEnabled = true; }
  46850. this.touchEnabled = touchEnabled;
  46851. /**
  46852. * Defines the buttons associated with the input to handle camera move.
  46853. */
  46854. this.buttons = [0, 1, 2];
  46855. /**
  46856. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46857. */
  46858. this.angularSensibility = 2000.0;
  46859. this.previousPosition = null;
  46860. }
  46861. /**
  46862. * Attach the input controls to a specific dom element to get the input from.
  46863. * @param element Defines the element the controls should be listened from
  46864. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46865. */
  46866. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46867. var _this = this;
  46868. var engine = this.camera.getEngine();
  46869. if (!this._pointerInput) {
  46870. this._pointerInput = function (p, s) {
  46871. var evt = p.event;
  46872. if (engine.isInVRExclusivePointerMode) {
  46873. return;
  46874. }
  46875. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46876. return;
  46877. }
  46878. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46879. return;
  46880. }
  46881. var srcElement = (evt.srcElement || evt.target);
  46882. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46883. try {
  46884. srcElement.setPointerCapture(evt.pointerId);
  46885. }
  46886. catch (e) {
  46887. //Nothing to do with the error. Execution will continue.
  46888. }
  46889. _this.previousPosition = {
  46890. x: evt.clientX,
  46891. y: evt.clientY
  46892. };
  46893. if (!noPreventDefault) {
  46894. evt.preventDefault();
  46895. element.focus();
  46896. }
  46897. }
  46898. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46899. try {
  46900. srcElement.releasePointerCapture(evt.pointerId);
  46901. }
  46902. catch (e) {
  46903. //Nothing to do with the error.
  46904. }
  46905. _this.previousPosition = null;
  46906. if (!noPreventDefault) {
  46907. evt.preventDefault();
  46908. }
  46909. }
  46910. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46911. if (!_this.previousPosition || engine.isPointerLock) {
  46912. return;
  46913. }
  46914. var offsetX = evt.clientX - _this.previousPosition.x;
  46915. if (_this.camera.getScene().useRightHandedSystem)
  46916. offsetX *= -1;
  46917. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46918. offsetX *= -1;
  46919. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46920. var offsetY = evt.clientY - _this.previousPosition.y;
  46921. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46922. _this.previousPosition = {
  46923. x: evt.clientX,
  46924. y: evt.clientY
  46925. };
  46926. if (!noPreventDefault) {
  46927. evt.preventDefault();
  46928. }
  46929. }
  46930. };
  46931. }
  46932. this._onMouseMove = function (evt) {
  46933. if (!engine.isPointerLock) {
  46934. return;
  46935. }
  46936. if (engine.isInVRExclusivePointerMode) {
  46937. return;
  46938. }
  46939. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46940. if (_this.camera.getScene().useRightHandedSystem)
  46941. offsetX *= -1;
  46942. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46943. offsetX *= -1;
  46944. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46945. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46946. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46947. _this.previousPosition = null;
  46948. if (!noPreventDefault) {
  46949. evt.preventDefault();
  46950. }
  46951. };
  46952. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46953. element.addEventListener("mousemove", this._onMouseMove, false);
  46954. };
  46955. /**
  46956. * Detach the current controls from the specified dom element.
  46957. * @param element Defines the element to stop listening the inputs from
  46958. */
  46959. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46960. if (this._observer && element) {
  46961. this.camera.getScene().onPointerObservable.remove(this._observer);
  46962. if (this._onMouseMove) {
  46963. element.removeEventListener("mousemove", this._onMouseMove);
  46964. }
  46965. this._observer = null;
  46966. this._onMouseMove = null;
  46967. this.previousPosition = null;
  46968. }
  46969. };
  46970. /**
  46971. * Gets the class name of the current intput.
  46972. * @returns the class name
  46973. */
  46974. FreeCameraMouseInput.prototype.getClassName = function () {
  46975. return "FreeCameraMouseInput";
  46976. };
  46977. /**
  46978. * Get the friendly name associated with the input class.
  46979. * @returns the input friendly name
  46980. */
  46981. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46982. return "mouse";
  46983. };
  46984. __decorate([
  46985. BABYLON.serialize()
  46986. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46987. __decorate([
  46988. BABYLON.serialize()
  46989. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46990. return FreeCameraMouseInput;
  46991. }());
  46992. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46993. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46994. })(BABYLON || (BABYLON = {}));
  46995. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46996. var BABYLON;
  46997. (function (BABYLON) {
  46998. /**
  46999. * Manage the keyboard inputs to control the movement of a free camera.
  47000. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47001. */
  47002. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47003. function FreeCameraKeyboardMoveInput() {
  47004. /**
  47005. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47006. */
  47007. this.keysUp = [38];
  47008. /**
  47009. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47010. */
  47011. this.keysDown = [40];
  47012. /**
  47013. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47014. */
  47015. this.keysLeft = [37];
  47016. /**
  47017. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47018. */
  47019. this.keysRight = [39];
  47020. this._keys = new Array();
  47021. }
  47022. /**
  47023. * Attach the input controls to a specific dom element to get the input from.
  47024. * @param element Defines the element the controls should be listened from
  47025. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47026. */
  47027. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47028. var _this = this;
  47029. if (this._onCanvasBlurObserver) {
  47030. return;
  47031. }
  47032. this._scene = this.camera.getScene();
  47033. this._engine = this._scene.getEngine();
  47034. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47035. _this._keys = [];
  47036. });
  47037. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47038. var evt = info.event;
  47039. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47040. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47041. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47042. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47043. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47044. var index = _this._keys.indexOf(evt.keyCode);
  47045. if (index === -1) {
  47046. _this._keys.push(evt.keyCode);
  47047. }
  47048. if (!noPreventDefault) {
  47049. evt.preventDefault();
  47050. }
  47051. }
  47052. }
  47053. else {
  47054. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47055. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47056. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47057. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47058. var index = _this._keys.indexOf(evt.keyCode);
  47059. if (index >= 0) {
  47060. _this._keys.splice(index, 1);
  47061. }
  47062. if (!noPreventDefault) {
  47063. evt.preventDefault();
  47064. }
  47065. }
  47066. }
  47067. });
  47068. };
  47069. /**
  47070. * Detach the current controls from the specified dom element.
  47071. * @param element Defines the element to stop listening the inputs from
  47072. */
  47073. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47074. if (this._scene) {
  47075. if (this._onKeyboardObserver) {
  47076. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47077. }
  47078. if (this._onCanvasBlurObserver) {
  47079. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47080. }
  47081. this._onKeyboardObserver = null;
  47082. this._onCanvasBlurObserver = null;
  47083. }
  47084. this._keys = [];
  47085. };
  47086. /**
  47087. * Update the current camera state depending on the inputs that have been used this frame.
  47088. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47089. */
  47090. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47091. if (this._onKeyboardObserver) {
  47092. var camera = this.camera;
  47093. // Keyboard
  47094. for (var index = 0; index < this._keys.length; index++) {
  47095. var keyCode = this._keys[index];
  47096. var speed = camera._computeLocalCameraSpeed();
  47097. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47098. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47099. }
  47100. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47101. camera._localDirection.copyFromFloats(0, 0, speed);
  47102. }
  47103. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47104. camera._localDirection.copyFromFloats(speed, 0, 0);
  47105. }
  47106. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47107. camera._localDirection.copyFromFloats(0, 0, -speed);
  47108. }
  47109. if (camera.getScene().useRightHandedSystem) {
  47110. camera._localDirection.z *= -1;
  47111. }
  47112. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47113. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47114. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47115. }
  47116. }
  47117. };
  47118. /**
  47119. * Gets the class name of the current intput.
  47120. * @returns the class name
  47121. */
  47122. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47123. return "FreeCameraKeyboardMoveInput";
  47124. };
  47125. /** @hidden */
  47126. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47127. this._keys = [];
  47128. };
  47129. /**
  47130. * Get the friendly name associated with the input class.
  47131. * @returns the input friendly name
  47132. */
  47133. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47134. return "keyboard";
  47135. };
  47136. __decorate([
  47137. BABYLON.serialize()
  47138. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47139. __decorate([
  47140. BABYLON.serialize()
  47141. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47142. __decorate([
  47143. BABYLON.serialize()
  47144. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47145. __decorate([
  47146. BABYLON.serialize()
  47147. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47148. return FreeCameraKeyboardMoveInput;
  47149. }());
  47150. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47151. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47152. })(BABYLON || (BABYLON = {}));
  47153. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47154. var BABYLON;
  47155. (function (BABYLON) {
  47156. /**
  47157. * Default Inputs manager for the FreeCamera.
  47158. * It groups all the default supported inputs for ease of use.
  47159. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47160. */
  47161. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47162. __extends(FreeCameraInputsManager, _super);
  47163. /**
  47164. * Instantiates a new FreeCameraInputsManager.
  47165. * @param camera Defines the camera the inputs belong to
  47166. */
  47167. function FreeCameraInputsManager(camera) {
  47168. return _super.call(this, camera) || this;
  47169. }
  47170. /**
  47171. * Add keyboard input support to the input manager.
  47172. * @returns the current input manager
  47173. */
  47174. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47175. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47176. return this;
  47177. };
  47178. /**
  47179. * Add mouse input support to the input manager.
  47180. * @returns the current input manager
  47181. */
  47182. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47183. if (touchEnabled === void 0) { touchEnabled = true; }
  47184. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47185. return this;
  47186. };
  47187. /**
  47188. * Add orientation input support to the input manager.
  47189. * @returns the current input manager
  47190. */
  47191. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47192. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47193. return this;
  47194. };
  47195. /**
  47196. * Add touch input support to the input manager.
  47197. * @returns the current input manager
  47198. */
  47199. FreeCameraInputsManager.prototype.addTouch = function () {
  47200. this.add(new BABYLON.FreeCameraTouchInput());
  47201. return this;
  47202. };
  47203. /**
  47204. * Add virtual joystick input support to the input manager.
  47205. * @returns the current input manager
  47206. */
  47207. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47208. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47209. return this;
  47210. };
  47211. return FreeCameraInputsManager;
  47212. }(BABYLON.CameraInputsManager));
  47213. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47214. })(BABYLON || (BABYLON = {}));
  47215. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47216. var BABYLON;
  47217. (function (BABYLON) {
  47218. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47219. // Forcing to use the Universal camera
  47220. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47221. });
  47222. /**
  47223. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47224. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  47225. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47226. */
  47227. var FreeCamera = /** @class */ (function (_super) {
  47228. __extends(FreeCamera, _super);
  47229. /**
  47230. * Instantiates a Free Camera.
  47231. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47232. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47233. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47234. * @param name Define the name of the camera in the scene
  47235. * @param position Define the start position of the camera in the scene
  47236. * @param scene Define the scene the camera belongs to
  47237. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47238. */
  47239. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47240. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47241. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47242. /**
  47243. * Define the collision ellipsoid of the camera.
  47244. * This is helpful to simulate a camera body like the player body around the camera
  47245. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47246. */
  47247. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47248. /**
  47249. * Define an offset for the position of the ellipsoid around the camera.
  47250. * This can be helpful to determine the center of the body near the gravity center of the body
  47251. * instead of its head.
  47252. */
  47253. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47254. /**
  47255. * Enable or disable collisions of the camera with the rest of the scene objects.
  47256. */
  47257. _this.checkCollisions = false;
  47258. /**
  47259. * Enable or disable gravity on the camera.
  47260. */
  47261. _this.applyGravity = false;
  47262. _this._needMoveForGravity = false;
  47263. _this._oldPosition = BABYLON.Vector3.Zero();
  47264. _this._diffPosition = BABYLON.Vector3.Zero();
  47265. _this._newPosition = BABYLON.Vector3.Zero();
  47266. // Collisions
  47267. _this._collisionMask = -1;
  47268. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47269. if (collidedMesh === void 0) { collidedMesh = null; }
  47270. //TODO move this to the collision coordinator!
  47271. if (_this.getScene().workerCollisions)
  47272. newPosition.multiplyInPlace(_this._collider._radius);
  47273. var updatePosition = function (newPos) {
  47274. _this._newPosition.copyFrom(newPos);
  47275. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47276. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47277. _this.position.addInPlace(_this._diffPosition);
  47278. if (_this.onCollide && collidedMesh) {
  47279. _this.onCollide(collidedMesh);
  47280. }
  47281. }
  47282. };
  47283. updatePosition(newPosition);
  47284. };
  47285. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47286. _this.inputs.addKeyboard().addMouse();
  47287. return _this;
  47288. }
  47289. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47290. /**
  47291. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47292. * Higher values reduce sensitivity.
  47293. */
  47294. get: function () {
  47295. var mouse = this.inputs.attached["mouse"];
  47296. if (mouse)
  47297. return mouse.angularSensibility;
  47298. return 0;
  47299. },
  47300. /**
  47301. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47302. * Higher values reduce sensitivity.
  47303. */
  47304. set: function (value) {
  47305. var mouse = this.inputs.attached["mouse"];
  47306. if (mouse)
  47307. mouse.angularSensibility = value;
  47308. },
  47309. enumerable: true,
  47310. configurable: true
  47311. });
  47312. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47313. /**
  47314. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47315. */
  47316. get: function () {
  47317. var keyboard = this.inputs.attached["keyboard"];
  47318. if (keyboard)
  47319. return keyboard.keysUp;
  47320. return [];
  47321. },
  47322. set: function (value) {
  47323. var keyboard = this.inputs.attached["keyboard"];
  47324. if (keyboard)
  47325. keyboard.keysUp = value;
  47326. },
  47327. enumerable: true,
  47328. configurable: true
  47329. });
  47330. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47331. /**
  47332. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47333. */
  47334. get: function () {
  47335. var keyboard = this.inputs.attached["keyboard"];
  47336. if (keyboard)
  47337. return keyboard.keysDown;
  47338. return [];
  47339. },
  47340. set: function (value) {
  47341. var keyboard = this.inputs.attached["keyboard"];
  47342. if (keyboard)
  47343. keyboard.keysDown = value;
  47344. },
  47345. enumerable: true,
  47346. configurable: true
  47347. });
  47348. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47349. /**
  47350. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47351. */
  47352. get: function () {
  47353. var keyboard = this.inputs.attached["keyboard"];
  47354. if (keyboard)
  47355. return keyboard.keysLeft;
  47356. return [];
  47357. },
  47358. set: function (value) {
  47359. var keyboard = this.inputs.attached["keyboard"];
  47360. if (keyboard)
  47361. keyboard.keysLeft = value;
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47367. /**
  47368. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47369. */
  47370. get: function () {
  47371. var keyboard = this.inputs.attached["keyboard"];
  47372. if (keyboard)
  47373. return keyboard.keysRight;
  47374. return [];
  47375. },
  47376. set: function (value) {
  47377. var keyboard = this.inputs.attached["keyboard"];
  47378. if (keyboard)
  47379. keyboard.keysRight = value;
  47380. },
  47381. enumerable: true,
  47382. configurable: true
  47383. });
  47384. /**
  47385. * Attached controls to the current camera.
  47386. * @param element Defines the element the controls should be listened from
  47387. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47388. */
  47389. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47390. this.inputs.attachElement(element, noPreventDefault);
  47391. };
  47392. /**
  47393. * Detach the current controls from the camera.
  47394. * The camera will stop reacting to inputs.
  47395. * @param element Defines the element to stop listening the inputs from
  47396. */
  47397. FreeCamera.prototype.detachControl = function (element) {
  47398. this.inputs.detachElement(element);
  47399. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47400. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47401. };
  47402. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47403. /**
  47404. * Define a collision mask to limit the list of object the camera can collide with
  47405. */
  47406. get: function () {
  47407. return this._collisionMask;
  47408. },
  47409. set: function (mask) {
  47410. this._collisionMask = !isNaN(mask) ? mask : -1;
  47411. },
  47412. enumerable: true,
  47413. configurable: true
  47414. });
  47415. /** @hidden */
  47416. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47417. var globalPosition;
  47418. if (this.parent) {
  47419. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47420. }
  47421. else {
  47422. globalPosition = this.position;
  47423. }
  47424. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47425. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47426. if (!this._collider) {
  47427. this._collider = new BABYLON.Collider();
  47428. }
  47429. this._collider._radius = this.ellipsoid;
  47430. this._collider.collisionMask = this._collisionMask;
  47431. //no need for clone, as long as gravity is not on.
  47432. var actualDisplacement = displacement;
  47433. //add gravity to the direction to prevent the dual-collision checking
  47434. if (this.applyGravity) {
  47435. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47436. actualDisplacement = displacement.add(this.getScene().gravity);
  47437. }
  47438. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47439. };
  47440. /** @hidden */
  47441. FreeCamera.prototype._checkInputs = function () {
  47442. if (!this._localDirection) {
  47443. this._localDirection = BABYLON.Vector3.Zero();
  47444. this._transformedDirection = BABYLON.Vector3.Zero();
  47445. }
  47446. this.inputs.checkInputs();
  47447. _super.prototype._checkInputs.call(this);
  47448. };
  47449. /** @hidden */
  47450. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47451. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47452. };
  47453. /** @hidden */
  47454. FreeCamera.prototype._updatePosition = function () {
  47455. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47456. this._collideWithWorld(this.cameraDirection);
  47457. }
  47458. else {
  47459. _super.prototype._updatePosition.call(this);
  47460. }
  47461. };
  47462. /**
  47463. * Destroy the camera and release the current resources hold by it.
  47464. */
  47465. FreeCamera.prototype.dispose = function () {
  47466. this.inputs.clear();
  47467. _super.prototype.dispose.call(this);
  47468. };
  47469. /**
  47470. * Gets the current object class name.
  47471. * @return the class name
  47472. */
  47473. FreeCamera.prototype.getClassName = function () {
  47474. return "FreeCamera";
  47475. };
  47476. __decorate([
  47477. BABYLON.serializeAsVector3()
  47478. ], FreeCamera.prototype, "ellipsoid", void 0);
  47479. __decorate([
  47480. BABYLON.serializeAsVector3()
  47481. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47482. __decorate([
  47483. BABYLON.serialize()
  47484. ], FreeCamera.prototype, "checkCollisions", void 0);
  47485. __decorate([
  47486. BABYLON.serialize()
  47487. ], FreeCamera.prototype, "applyGravity", void 0);
  47488. return FreeCamera;
  47489. }(BABYLON.TargetCamera));
  47490. BABYLON.FreeCamera = FreeCamera;
  47491. })(BABYLON || (BABYLON = {}));
  47492. //# sourceMappingURL=babylon.freeCamera.js.map
  47493. var BABYLON;
  47494. (function (BABYLON) {
  47495. /**
  47496. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47497. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47498. */
  47499. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47500. function ArcRotateCameraKeyboardMoveInput() {
  47501. /**
  47502. * Defines the list of key codes associated with the up action (increase alpha)
  47503. */
  47504. this.keysUp = [38];
  47505. /**
  47506. * Defines the list of key codes associated with the down action (decrease alpha)
  47507. */
  47508. this.keysDown = [40];
  47509. /**
  47510. * Defines the list of key codes associated with the left action (increase beta)
  47511. */
  47512. this.keysLeft = [37];
  47513. /**
  47514. * Defines the list of key codes associated with the right action (decrease beta)
  47515. */
  47516. this.keysRight = [39];
  47517. /**
  47518. * Defines the list of key codes associated with the reset action.
  47519. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47520. */
  47521. this.keysReset = [220];
  47522. /**
  47523. * Defines the panning sensibility of the inputs.
  47524. * (How fast is the camera paning)
  47525. */
  47526. this.panningSensibility = 50.0;
  47527. /**
  47528. * Defines the zooming sensibility of the inputs.
  47529. * (How fast is the camera zooming)
  47530. */
  47531. this.zoomingSensibility = 25.0;
  47532. /**
  47533. * Defines wether maintaining the alt key down switch the movement mode from
  47534. * orientation to zoom.
  47535. */
  47536. this.useAltToZoom = true;
  47537. this._keys = new Array();
  47538. }
  47539. /**
  47540. * Attach the input controls to a specific dom element to get the input from.
  47541. * @param element Defines the element the controls should be listened from
  47542. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47543. */
  47544. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47545. var _this = this;
  47546. if (this._onCanvasBlurObserver) {
  47547. return;
  47548. }
  47549. this._scene = this.camera.getScene();
  47550. this._engine = this._scene.getEngine();
  47551. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47552. _this._keys = [];
  47553. });
  47554. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47555. var evt = info.event;
  47556. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47557. _this._ctrlPressed = evt.ctrlKey;
  47558. _this._altPressed = evt.altKey;
  47559. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47560. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47561. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47562. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47563. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47564. var index = _this._keys.indexOf(evt.keyCode);
  47565. if (index === -1) {
  47566. _this._keys.push(evt.keyCode);
  47567. }
  47568. if (evt.preventDefault) {
  47569. if (!noPreventDefault) {
  47570. evt.preventDefault();
  47571. }
  47572. }
  47573. }
  47574. }
  47575. else {
  47576. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47577. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47578. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47579. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47580. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47581. var index = _this._keys.indexOf(evt.keyCode);
  47582. if (index >= 0) {
  47583. _this._keys.splice(index, 1);
  47584. }
  47585. if (evt.preventDefault) {
  47586. if (!noPreventDefault) {
  47587. evt.preventDefault();
  47588. }
  47589. }
  47590. }
  47591. }
  47592. });
  47593. };
  47594. /**
  47595. * Detach the current controls from the specified dom element.
  47596. * @param element Defines the element to stop listening the inputs from
  47597. */
  47598. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47599. if (this._scene) {
  47600. if (this._onKeyboardObserver) {
  47601. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47602. }
  47603. if (this._onCanvasBlurObserver) {
  47604. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47605. }
  47606. this._onKeyboardObserver = null;
  47607. this._onCanvasBlurObserver = null;
  47608. }
  47609. this._keys = [];
  47610. };
  47611. /**
  47612. * Update the current camera state depending on the inputs that have been used this frame.
  47613. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47614. */
  47615. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47616. if (this._onKeyboardObserver) {
  47617. var camera = this.camera;
  47618. for (var index = 0; index < this._keys.length; index++) {
  47619. var keyCode = this._keys[index];
  47620. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47621. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47622. camera.inertialPanningX -= 1 / this.panningSensibility;
  47623. }
  47624. else {
  47625. camera.inertialAlphaOffset -= 0.01;
  47626. }
  47627. }
  47628. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47629. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47630. camera.inertialPanningY += 1 / this.panningSensibility;
  47631. }
  47632. else if (this._altPressed && this.useAltToZoom) {
  47633. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47634. }
  47635. else {
  47636. camera.inertialBetaOffset -= 0.01;
  47637. }
  47638. }
  47639. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47640. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47641. camera.inertialPanningX += 1 / this.panningSensibility;
  47642. }
  47643. else {
  47644. camera.inertialAlphaOffset += 0.01;
  47645. }
  47646. }
  47647. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47648. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47649. camera.inertialPanningY -= 1 / this.panningSensibility;
  47650. }
  47651. else if (this._altPressed && this.useAltToZoom) {
  47652. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47653. }
  47654. else {
  47655. camera.inertialBetaOffset += 0.01;
  47656. }
  47657. }
  47658. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47659. if (camera.useInputToRestoreState) {
  47660. camera.restoreState();
  47661. }
  47662. }
  47663. }
  47664. }
  47665. };
  47666. /**
  47667. * Gets the class name of the current intput.
  47668. * @returns the class name
  47669. */
  47670. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47671. return "ArcRotateCameraKeyboardMoveInput";
  47672. };
  47673. /**
  47674. * Get the friendly name associated with the input class.
  47675. * @returns the input friendly name
  47676. */
  47677. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47678. return "keyboard";
  47679. };
  47680. __decorate([
  47681. BABYLON.serialize()
  47682. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47683. __decorate([
  47684. BABYLON.serialize()
  47685. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47686. __decorate([
  47687. BABYLON.serialize()
  47688. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47689. __decorate([
  47690. BABYLON.serialize()
  47691. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47692. __decorate([
  47693. BABYLON.serialize()
  47694. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47695. __decorate([
  47696. BABYLON.serialize()
  47697. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47698. __decorate([
  47699. BABYLON.serialize()
  47700. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47701. __decorate([
  47702. BABYLON.serialize()
  47703. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47704. return ArcRotateCameraKeyboardMoveInput;
  47705. }());
  47706. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47707. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47708. })(BABYLON || (BABYLON = {}));
  47709. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47710. var BABYLON;
  47711. (function (BABYLON) {
  47712. /**
  47713. * Manage the mouse wheel inputs to control an arc rotate camera.
  47714. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47715. */
  47716. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47717. function ArcRotateCameraMouseWheelInput() {
  47718. /**
  47719. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47720. */
  47721. this.wheelPrecision = 3.0;
  47722. /**
  47723. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47724. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47725. */
  47726. this.wheelDeltaPercentage = 0;
  47727. }
  47728. /**
  47729. * Attach the input controls to a specific dom element to get the input from.
  47730. * @param element Defines the element the controls should be listened from
  47731. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47732. */
  47733. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47734. var _this = this;
  47735. this._wheel = function (p, s) {
  47736. //sanity check - this should be a PointerWheel event.
  47737. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47738. return;
  47739. var event = p.event;
  47740. var delta = 0;
  47741. if (event.wheelDelta) {
  47742. if (_this.wheelDeltaPercentage) {
  47743. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47744. if (event.wheelDelta > 0) {
  47745. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47746. }
  47747. else {
  47748. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47749. }
  47750. }
  47751. else {
  47752. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47753. }
  47754. }
  47755. else if (event.detail) {
  47756. delta = -event.detail / _this.wheelPrecision;
  47757. }
  47758. if (delta)
  47759. _this.camera.inertialRadiusOffset += delta;
  47760. if (event.preventDefault) {
  47761. if (!noPreventDefault) {
  47762. event.preventDefault();
  47763. }
  47764. }
  47765. };
  47766. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47767. };
  47768. /**
  47769. * Detach the current controls from the specified dom element.
  47770. * @param element Defines the element to stop listening the inputs from
  47771. */
  47772. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47773. if (this._observer && element) {
  47774. this.camera.getScene().onPointerObservable.remove(this._observer);
  47775. this._observer = null;
  47776. this._wheel = null;
  47777. }
  47778. };
  47779. /**
  47780. * Gets the class name of the current intput.
  47781. * @returns the class name
  47782. */
  47783. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47784. return "ArcRotateCameraMouseWheelInput";
  47785. };
  47786. /**
  47787. * Get the friendly name associated with the input class.
  47788. * @returns the input friendly name
  47789. */
  47790. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47791. return "mousewheel";
  47792. };
  47793. __decorate([
  47794. BABYLON.serialize()
  47795. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47796. __decorate([
  47797. BABYLON.serialize()
  47798. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47799. return ArcRotateCameraMouseWheelInput;
  47800. }());
  47801. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47802. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47803. })(BABYLON || (BABYLON = {}));
  47804. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47805. var BABYLON;
  47806. (function (BABYLON) {
  47807. /**
  47808. * Manage the pointers inputs to control an arc rotate camera.
  47809. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47810. */
  47811. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47812. function ArcRotateCameraPointersInput() {
  47813. /**
  47814. * Defines the buttons associated with the input to handle camera move.
  47815. */
  47816. this.buttons = [0, 1, 2];
  47817. /**
  47818. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47819. */
  47820. this.angularSensibilityX = 1000.0;
  47821. /**
  47822. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47823. */
  47824. this.angularSensibilityY = 1000.0;
  47825. /**
  47826. * Defines the pointer pinch precision or how fast is the camera zooming.
  47827. */
  47828. this.pinchPrecision = 12.0;
  47829. /**
  47830. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47831. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47832. */
  47833. this.pinchDeltaPercentage = 0;
  47834. /**
  47835. * Defines the pointer panning sensibility or how fast is the camera moving.
  47836. */
  47837. this.panningSensibility = 1000.0;
  47838. /**
  47839. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47840. */
  47841. this.multiTouchPanning = true;
  47842. /**
  47843. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47844. */
  47845. this.multiTouchPanAndZoom = true;
  47846. /**
  47847. * Revers pinch action direction.
  47848. */
  47849. this.pinchInwards = true;
  47850. this._isPanClick = false;
  47851. }
  47852. /**
  47853. * Attach the input controls to a specific dom element to get the input from.
  47854. * @param element Defines the element the controls should be listened from
  47855. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47856. */
  47857. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47858. var _this = this;
  47859. var engine = this.camera.getEngine();
  47860. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47861. var pointA = null;
  47862. var pointB = null;
  47863. var previousPinchSquaredDistance = 0;
  47864. var initialDistance = 0;
  47865. var twoFingerActivityCount = 0;
  47866. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47867. this._pointerInput = function (p, s) {
  47868. var evt = p.event;
  47869. var isTouch = p.event.pointerType === "touch";
  47870. if (engine.isInVRExclusivePointerMode) {
  47871. return;
  47872. }
  47873. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47874. return;
  47875. }
  47876. var srcElement = (evt.srcElement || evt.target);
  47877. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47878. try {
  47879. srcElement.setPointerCapture(evt.pointerId);
  47880. }
  47881. catch (e) {
  47882. //Nothing to do with the error. Execution will continue.
  47883. }
  47884. // Manage panning with pan button click
  47885. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47886. // manage pointers
  47887. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47888. if (pointA === null) {
  47889. pointA = cacheSoloPointer;
  47890. }
  47891. else if (pointB === null) {
  47892. pointB = cacheSoloPointer;
  47893. }
  47894. if (!noPreventDefault) {
  47895. evt.preventDefault();
  47896. element.focus();
  47897. }
  47898. }
  47899. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47900. if (_this.camera.useInputToRestoreState) {
  47901. _this.camera.restoreState();
  47902. }
  47903. }
  47904. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47905. try {
  47906. srcElement.releasePointerCapture(evt.pointerId);
  47907. }
  47908. catch (e) {
  47909. //Nothing to do with the error.
  47910. }
  47911. cacheSoloPointer = null;
  47912. previousPinchSquaredDistance = 0;
  47913. previousMultiTouchPanPosition.isPaning = false;
  47914. previousMultiTouchPanPosition.isPinching = false;
  47915. twoFingerActivityCount = 0;
  47916. initialDistance = 0;
  47917. if (!isTouch) {
  47918. pointB = null; // Mouse and pen are mono pointer
  47919. }
  47920. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47921. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47922. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47923. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47924. if (engine._badOS) {
  47925. pointA = pointB = null;
  47926. }
  47927. else {
  47928. //only remove the impacted pointer in case of multitouch allowing on most
  47929. //platforms switching from rotate to zoom and pan seamlessly.
  47930. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47931. pointA = pointB;
  47932. pointB = null;
  47933. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47934. }
  47935. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47936. pointB = null;
  47937. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47938. }
  47939. else {
  47940. pointA = pointB = null;
  47941. }
  47942. }
  47943. if (!noPreventDefault) {
  47944. evt.preventDefault();
  47945. }
  47946. }
  47947. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47948. if (!noPreventDefault) {
  47949. evt.preventDefault();
  47950. }
  47951. // One button down
  47952. if (pointA && pointB === null && cacheSoloPointer) {
  47953. if (_this.panningSensibility !== 0 &&
  47954. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47955. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47956. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47957. }
  47958. else {
  47959. var offsetX = evt.clientX - cacheSoloPointer.x;
  47960. var offsetY = evt.clientY - cacheSoloPointer.y;
  47961. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47962. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47963. }
  47964. cacheSoloPointer.x = evt.clientX;
  47965. cacheSoloPointer.y = evt.clientY;
  47966. }
  47967. // Two buttons down: pinch/pan
  47968. else if (pointA && pointB) {
  47969. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47970. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47971. ed.x = evt.clientX;
  47972. ed.y = evt.clientY;
  47973. var direction = _this.pinchInwards ? 1 : -1;
  47974. var distX = pointA.x - pointB.x;
  47975. var distY = pointA.y - pointB.y;
  47976. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47977. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47978. if (previousPinchSquaredDistance === 0) {
  47979. initialDistance = pinchDistance;
  47980. previousPinchSquaredDistance = pinchSquaredDistance;
  47981. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47982. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47983. return;
  47984. }
  47985. if (_this.multiTouchPanAndZoom) {
  47986. if (_this.pinchDeltaPercentage) {
  47987. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47988. }
  47989. else {
  47990. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47991. (_this.pinchPrecision *
  47992. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47993. direction);
  47994. }
  47995. if (_this.panningSensibility !== 0) {
  47996. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47997. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47998. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47999. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48000. previousMultiTouchPanPosition.x = pointersCenterX;
  48001. previousMultiTouchPanPosition.y = pointersCenterY;
  48002. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48003. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48004. }
  48005. }
  48006. else {
  48007. twoFingerActivityCount++;
  48008. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48009. if (_this.pinchDeltaPercentage) {
  48010. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48011. }
  48012. else {
  48013. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48014. (_this.pinchPrecision *
  48015. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48016. direction);
  48017. }
  48018. previousMultiTouchPanPosition.isPaning = false;
  48019. previousMultiTouchPanPosition.isPinching = true;
  48020. }
  48021. else {
  48022. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48023. if (!previousMultiTouchPanPosition.isPaning) {
  48024. previousMultiTouchPanPosition.isPaning = true;
  48025. previousMultiTouchPanPosition.isPinching = false;
  48026. previousMultiTouchPanPosition.x = ed.x;
  48027. previousMultiTouchPanPosition.y = ed.y;
  48028. return;
  48029. }
  48030. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48031. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48032. }
  48033. }
  48034. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48035. previousMultiTouchPanPosition.x = ed.x;
  48036. previousMultiTouchPanPosition.y = ed.y;
  48037. }
  48038. }
  48039. previousPinchSquaredDistance = pinchSquaredDistance;
  48040. }
  48041. }
  48042. };
  48043. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  48044. this._onContextMenu = function (evt) {
  48045. evt.preventDefault();
  48046. };
  48047. if (!this.camera._useCtrlForPanning) {
  48048. element.addEventListener("contextmenu", this._onContextMenu, false);
  48049. }
  48050. this._onLostFocus = function () {
  48051. //this._keys = [];
  48052. pointA = pointB = null;
  48053. previousPinchSquaredDistance = 0;
  48054. previousMultiTouchPanPosition.isPaning = false;
  48055. previousMultiTouchPanPosition.isPinching = false;
  48056. twoFingerActivityCount = 0;
  48057. cacheSoloPointer = null;
  48058. initialDistance = 0;
  48059. };
  48060. this._onMouseMove = function (evt) {
  48061. if (!engine.isPointerLock) {
  48062. return;
  48063. }
  48064. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48065. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48066. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48067. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48068. if (!noPreventDefault) {
  48069. evt.preventDefault();
  48070. }
  48071. };
  48072. this._onGestureStart = function (e) {
  48073. if (window.MSGesture === undefined) {
  48074. return;
  48075. }
  48076. if (!_this._MSGestureHandler) {
  48077. _this._MSGestureHandler = new MSGesture();
  48078. _this._MSGestureHandler.target = element;
  48079. }
  48080. _this._MSGestureHandler.addPointer(e.pointerId);
  48081. };
  48082. this._onGesture = function (e) {
  48083. _this.camera.radius *= e.scale;
  48084. if (e.preventDefault) {
  48085. if (!noPreventDefault) {
  48086. e.stopPropagation();
  48087. e.preventDefault();
  48088. }
  48089. }
  48090. };
  48091. element.addEventListener("mousemove", this._onMouseMove, false);
  48092. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48093. element.addEventListener("MSGestureChange", this._onGesture, false);
  48094. BABYLON.Tools.RegisterTopRootEvents([
  48095. { name: "blur", handler: this._onLostFocus }
  48096. ]);
  48097. };
  48098. /**
  48099. * Detach the current controls from the specified dom element.
  48100. * @param element Defines the element to stop listening the inputs from
  48101. */
  48102. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48103. if (this._onLostFocus) {
  48104. BABYLON.Tools.UnregisterTopRootEvents([
  48105. { name: "blur", handler: this._onLostFocus }
  48106. ]);
  48107. }
  48108. if (element && this._observer) {
  48109. this.camera.getScene().onPointerObservable.remove(this._observer);
  48110. this._observer = null;
  48111. if (this._onContextMenu) {
  48112. element.removeEventListener("contextmenu", this._onContextMenu);
  48113. }
  48114. if (this._onMouseMove) {
  48115. element.removeEventListener("mousemove", this._onMouseMove);
  48116. }
  48117. if (this._onGestureStart) {
  48118. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48119. }
  48120. if (this._onGesture) {
  48121. element.removeEventListener("MSGestureChange", this._onGesture);
  48122. }
  48123. this._isPanClick = false;
  48124. this.pinchInwards = true;
  48125. this._onMouseMove = null;
  48126. this._onGestureStart = null;
  48127. this._onGesture = null;
  48128. this._MSGestureHandler = null;
  48129. this._onLostFocus = null;
  48130. this._onContextMenu = null;
  48131. }
  48132. };
  48133. /**
  48134. * Gets the class name of the current intput.
  48135. * @returns the class name
  48136. */
  48137. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48138. return "ArcRotateCameraPointersInput";
  48139. };
  48140. /**
  48141. * Get the friendly name associated with the input class.
  48142. * @returns the input friendly name
  48143. */
  48144. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48145. return "pointers";
  48146. };
  48147. __decorate([
  48148. BABYLON.serialize()
  48149. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48150. __decorate([
  48151. BABYLON.serialize()
  48152. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48153. __decorate([
  48154. BABYLON.serialize()
  48155. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48156. __decorate([
  48157. BABYLON.serialize()
  48158. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48159. __decorate([
  48160. BABYLON.serialize()
  48161. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48162. __decorate([
  48163. BABYLON.serialize()
  48164. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48165. __decorate([
  48166. BABYLON.serialize()
  48167. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48171. return ArcRotateCameraPointersInput;
  48172. }());
  48173. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48174. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48175. })(BABYLON || (BABYLON = {}));
  48176. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48177. var BABYLON;
  48178. (function (BABYLON) {
  48179. /**
  48180. * Default Inputs manager for the ArcRotateCamera.
  48181. * It groups all the default supported inputs for ease of use.
  48182. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48183. */
  48184. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48185. __extends(ArcRotateCameraInputsManager, _super);
  48186. /**
  48187. * Instantiates a new ArcRotateCameraInputsManager.
  48188. * @param camera Defines the camera the inputs belong to
  48189. */
  48190. function ArcRotateCameraInputsManager(camera) {
  48191. return _super.call(this, camera) || this;
  48192. }
  48193. /**
  48194. * Add mouse wheel input support to the input manager.
  48195. * @returns the current input manager
  48196. */
  48197. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48198. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48199. return this;
  48200. };
  48201. /**
  48202. * Add pointers input support to the input manager.
  48203. * @returns the current input manager
  48204. */
  48205. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48206. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48207. return this;
  48208. };
  48209. /**
  48210. * Add keyboard input support to the input manager.
  48211. * @returns the current input manager
  48212. */
  48213. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48214. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48215. return this;
  48216. };
  48217. /**
  48218. * Add orientation input support to the input manager.
  48219. * @returns the current input manager
  48220. */
  48221. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48222. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48223. return this;
  48224. };
  48225. return ArcRotateCameraInputsManager;
  48226. }(BABYLON.CameraInputsManager));
  48227. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48228. })(BABYLON || (BABYLON = {}));
  48229. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48230. var BABYLON;
  48231. (function (BABYLON) {
  48232. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  48233. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48234. });
  48235. /**
  48236. * This represents an orbital type of camera.
  48237. *
  48238. * 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.
  48239. * 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.
  48240. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48241. */
  48242. var ArcRotateCamera = /** @class */ (function (_super) {
  48243. __extends(ArcRotateCamera, _super);
  48244. /**
  48245. * Instantiates a new ArcRotateCamera in a given scene
  48246. * @param name Defines the name of the camera
  48247. * @param alpha Defines the camera rotation along the logitudinal axis
  48248. * @param beta Defines the camera rotation along the latitudinal axis
  48249. * @param radius Defines the camera distance from its target
  48250. * @param target Defines the camera target
  48251. * @param scene Defines the scene the camera belongs to
  48252. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48253. */
  48254. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48255. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48256. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48257. /**
  48258. * Current inertia value on the longitudinal axis.
  48259. * The bigger this number the longer it will take for the camera to stop.
  48260. */
  48261. _this.inertialAlphaOffset = 0;
  48262. /**
  48263. * Current inertia value on the latitudinal axis.
  48264. * The bigger this number the longer it will take for the camera to stop.
  48265. */
  48266. _this.inertialBetaOffset = 0;
  48267. /**
  48268. * Current inertia value on the radius axis.
  48269. * The bigger this number the longer it will take for the camera to stop.
  48270. */
  48271. _this.inertialRadiusOffset = 0;
  48272. /**
  48273. * Minimum allowed angle on the longitudinal axis.
  48274. * This can help limiting how the Camera is able to move in the scene.
  48275. */
  48276. _this.lowerAlphaLimit = null;
  48277. /**
  48278. * Maximum allowed angle on the longitudinal axis.
  48279. * This can help limiting how the Camera is able to move in the scene.
  48280. */
  48281. _this.upperAlphaLimit = null;
  48282. /**
  48283. * Minimum allowed angle on the latitudinal axis.
  48284. * This can help limiting how the Camera is able to move in the scene.
  48285. */
  48286. _this.lowerBetaLimit = 0.01;
  48287. /**
  48288. * Maximum allowed angle on the latitudinal axis.
  48289. * This can help limiting how the Camera is able to move in the scene.
  48290. */
  48291. _this.upperBetaLimit = Math.PI;
  48292. /**
  48293. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48294. * This can help limiting how the Camera is able to move in the scene.
  48295. */
  48296. _this.lowerRadiusLimit = null;
  48297. /**
  48298. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48299. * This can help limiting how the Camera is able to move in the scene.
  48300. */
  48301. _this.upperRadiusLimit = null;
  48302. /**
  48303. * Defines the current inertia value used during panning of the camera along the X axis.
  48304. */
  48305. _this.inertialPanningX = 0;
  48306. /**
  48307. * Defines the current inertia value used during panning of the camera along the Y axis.
  48308. */
  48309. _this.inertialPanningY = 0;
  48310. /**
  48311. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48312. * Basically if your fingers moves away from more than this distance you will be considered
  48313. * in pinch mode.
  48314. */
  48315. _this.pinchToPanMaxDistance = 20;
  48316. /**
  48317. * Defines the maximum distance the camera can pan.
  48318. * This could help keeping the cammera always in your scene.
  48319. */
  48320. _this.panningDistanceLimit = null;
  48321. /**
  48322. * Defines the target of the camera before paning.
  48323. */
  48324. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48325. /**
  48326. * Defines the value of the inertia used during panning.
  48327. * 0 would mean stop inertia and one would mean no decelleration at all.
  48328. */
  48329. _this.panningInertia = 0.9;
  48330. //-- end properties for backward compatibility for inputs
  48331. /**
  48332. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48333. */
  48334. _this.zoomOnFactor = 1;
  48335. /**
  48336. * Defines a screen offset for the camera position.
  48337. */
  48338. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48339. /**
  48340. * Allows the camera to be completely reversed.
  48341. * If false the camera can not arrive upside down.
  48342. */
  48343. _this.allowUpsideDown = true;
  48344. /**
  48345. * Define if double tap/click is used to restore the previously saved state of the camera.
  48346. */
  48347. _this.useInputToRestoreState = true;
  48348. /** @hidden */
  48349. _this._viewMatrix = new BABYLON.Matrix();
  48350. /**
  48351. * Defines the allowed panning axis.
  48352. */
  48353. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48354. /**
  48355. * Observable triggered when the mesh target has been changed on the camera.
  48356. */
  48357. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48358. /**
  48359. * Defines whether the camera should check collision with the objects oh the scene.
  48360. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48361. */
  48362. _this.checkCollisions = false;
  48363. /**
  48364. * Defines the collision radius of the camera.
  48365. * This simulates a sphere around the camera.
  48366. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48367. */
  48368. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48369. _this._previousPosition = BABYLON.Vector3.Zero();
  48370. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48371. _this._newPosition = BABYLON.Vector3.Zero();
  48372. _this._computationVector = BABYLON.Vector3.Zero();
  48373. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48374. if (collidedMesh === void 0) { collidedMesh = null; }
  48375. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48376. newPosition.multiplyInPlace(_this._collider._radius);
  48377. }
  48378. if (!collidedMesh) {
  48379. _this._previousPosition.copyFrom(_this.position);
  48380. }
  48381. else {
  48382. _this.setPosition(newPosition);
  48383. if (_this.onCollide) {
  48384. _this.onCollide(collidedMesh);
  48385. }
  48386. }
  48387. // Recompute because of constraints
  48388. var cosa = Math.cos(_this.alpha);
  48389. var sina = Math.sin(_this.alpha);
  48390. var cosb = Math.cos(_this.beta);
  48391. var sinb = Math.sin(_this.beta);
  48392. if (sinb === 0) {
  48393. sinb = 0.0001;
  48394. }
  48395. var target = _this._getTargetPosition();
  48396. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48397. target.addToRef(_this._computationVector, _this._newPosition);
  48398. _this.position.copyFrom(_this._newPosition);
  48399. var up = _this.upVector;
  48400. if (_this.allowUpsideDown && _this.beta < 0) {
  48401. up = up.clone();
  48402. up = up.negate();
  48403. }
  48404. _this._computeViewMatrix(_this.position, target, up);
  48405. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48406. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48407. _this._collisionTriggered = false;
  48408. };
  48409. _this._target = BABYLON.Vector3.Zero();
  48410. if (target) {
  48411. _this.setTarget(target);
  48412. }
  48413. _this.alpha = alpha;
  48414. _this.beta = beta;
  48415. _this.radius = radius;
  48416. _this.getViewMatrix();
  48417. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48418. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48419. return _this;
  48420. }
  48421. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48422. /**
  48423. * Defines the target point of the camera.
  48424. * The camera looks towards it form the radius distance.
  48425. */
  48426. get: function () {
  48427. return this._target;
  48428. },
  48429. set: function (value) {
  48430. this.setTarget(value);
  48431. },
  48432. enumerable: true,
  48433. configurable: true
  48434. });
  48435. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48436. //-- begin properties for backward compatibility for inputs
  48437. /**
  48438. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48439. */
  48440. get: function () {
  48441. var pointers = this.inputs.attached["pointers"];
  48442. if (pointers)
  48443. return pointers.angularSensibilityX;
  48444. return 0;
  48445. },
  48446. set: function (value) {
  48447. var pointers = this.inputs.attached["pointers"];
  48448. if (pointers) {
  48449. pointers.angularSensibilityX = value;
  48450. }
  48451. },
  48452. enumerable: true,
  48453. configurable: true
  48454. });
  48455. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48456. /**
  48457. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48458. */
  48459. get: function () {
  48460. var pointers = this.inputs.attached["pointers"];
  48461. if (pointers)
  48462. return pointers.angularSensibilityY;
  48463. return 0;
  48464. },
  48465. set: function (value) {
  48466. var pointers = this.inputs.attached["pointers"];
  48467. if (pointers) {
  48468. pointers.angularSensibilityY = value;
  48469. }
  48470. },
  48471. enumerable: true,
  48472. configurable: true
  48473. });
  48474. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48475. /**
  48476. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48477. */
  48478. get: function () {
  48479. var pointers = this.inputs.attached["pointers"];
  48480. if (pointers)
  48481. return pointers.pinchPrecision;
  48482. return 0;
  48483. },
  48484. set: function (value) {
  48485. var pointers = this.inputs.attached["pointers"];
  48486. if (pointers) {
  48487. pointers.pinchPrecision = value;
  48488. }
  48489. },
  48490. enumerable: true,
  48491. configurable: true
  48492. });
  48493. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48494. /**
  48495. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48496. * It will be used instead of pinchDeltaPrecision if different from 0.
  48497. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48498. */
  48499. get: function () {
  48500. var pointers = this.inputs.attached["pointers"];
  48501. if (pointers)
  48502. return pointers.pinchDeltaPercentage;
  48503. return 0;
  48504. },
  48505. set: function (value) {
  48506. var pointers = this.inputs.attached["pointers"];
  48507. if (pointers) {
  48508. pointers.pinchDeltaPercentage = value;
  48509. }
  48510. },
  48511. enumerable: true,
  48512. configurable: true
  48513. });
  48514. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48515. /**
  48516. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48517. */
  48518. get: function () {
  48519. var pointers = this.inputs.attached["pointers"];
  48520. if (pointers)
  48521. return pointers.panningSensibility;
  48522. return 0;
  48523. },
  48524. set: function (value) {
  48525. var pointers = this.inputs.attached["pointers"];
  48526. if (pointers) {
  48527. pointers.panningSensibility = value;
  48528. }
  48529. },
  48530. enumerable: true,
  48531. configurable: true
  48532. });
  48533. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48534. /**
  48535. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48536. */
  48537. get: function () {
  48538. var keyboard = this.inputs.attached["keyboard"];
  48539. if (keyboard)
  48540. return keyboard.keysUp;
  48541. return [];
  48542. },
  48543. set: function (value) {
  48544. var keyboard = this.inputs.attached["keyboard"];
  48545. if (keyboard)
  48546. keyboard.keysUp = value;
  48547. },
  48548. enumerable: true,
  48549. configurable: true
  48550. });
  48551. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48552. /**
  48553. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48554. */
  48555. get: function () {
  48556. var keyboard = this.inputs.attached["keyboard"];
  48557. if (keyboard)
  48558. return keyboard.keysDown;
  48559. return [];
  48560. },
  48561. set: function (value) {
  48562. var keyboard = this.inputs.attached["keyboard"];
  48563. if (keyboard)
  48564. keyboard.keysDown = value;
  48565. },
  48566. enumerable: true,
  48567. configurable: true
  48568. });
  48569. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48570. /**
  48571. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48572. */
  48573. get: function () {
  48574. var keyboard = this.inputs.attached["keyboard"];
  48575. if (keyboard)
  48576. return keyboard.keysLeft;
  48577. return [];
  48578. },
  48579. set: function (value) {
  48580. var keyboard = this.inputs.attached["keyboard"];
  48581. if (keyboard)
  48582. keyboard.keysLeft = value;
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48588. /**
  48589. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48590. */
  48591. get: function () {
  48592. var keyboard = this.inputs.attached["keyboard"];
  48593. if (keyboard)
  48594. return keyboard.keysRight;
  48595. return [];
  48596. },
  48597. set: function (value) {
  48598. var keyboard = this.inputs.attached["keyboard"];
  48599. if (keyboard)
  48600. keyboard.keysRight = value;
  48601. },
  48602. enumerable: true,
  48603. configurable: true
  48604. });
  48605. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48606. /**
  48607. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48608. */
  48609. get: function () {
  48610. var mousewheel = this.inputs.attached["mousewheel"];
  48611. if (mousewheel)
  48612. return mousewheel.wheelPrecision;
  48613. return 0;
  48614. },
  48615. set: function (value) {
  48616. var mousewheel = this.inputs.attached["mousewheel"];
  48617. if (mousewheel)
  48618. mousewheel.wheelPrecision = value;
  48619. },
  48620. enumerable: true,
  48621. configurable: true
  48622. });
  48623. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48624. /**
  48625. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48626. * It will be used instead of pinchDeltaPrecision if different from 0.
  48627. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48628. */
  48629. get: function () {
  48630. var mousewheel = this.inputs.attached["mousewheel"];
  48631. if (mousewheel)
  48632. return mousewheel.wheelDeltaPercentage;
  48633. return 0;
  48634. },
  48635. set: function (value) {
  48636. var mousewheel = this.inputs.attached["mousewheel"];
  48637. if (mousewheel)
  48638. mousewheel.wheelDeltaPercentage = value;
  48639. },
  48640. enumerable: true,
  48641. configurable: true
  48642. });
  48643. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48644. /**
  48645. * Gets the bouncing behavior of the camera if it has been enabled.
  48646. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48647. */
  48648. get: function () {
  48649. return this._bouncingBehavior;
  48650. },
  48651. enumerable: true,
  48652. configurable: true
  48653. });
  48654. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48655. /**
  48656. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48657. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48658. */
  48659. get: function () {
  48660. return this._bouncingBehavior != null;
  48661. },
  48662. set: function (value) {
  48663. if (value === this.useBouncingBehavior) {
  48664. return;
  48665. }
  48666. if (value) {
  48667. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48668. this.addBehavior(this._bouncingBehavior);
  48669. }
  48670. else if (this._bouncingBehavior) {
  48671. this.removeBehavior(this._bouncingBehavior);
  48672. this._bouncingBehavior = null;
  48673. }
  48674. },
  48675. enumerable: true,
  48676. configurable: true
  48677. });
  48678. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48679. /**
  48680. * Gets the framing behavior of the camera if it has been enabled.
  48681. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48682. */
  48683. get: function () {
  48684. return this._framingBehavior;
  48685. },
  48686. enumerable: true,
  48687. configurable: true
  48688. });
  48689. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48690. /**
  48691. * Defines if the framing behavior of the camera is enabled on the camera.
  48692. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48693. */
  48694. get: function () {
  48695. return this._framingBehavior != null;
  48696. },
  48697. set: function (value) {
  48698. if (value === this.useFramingBehavior) {
  48699. return;
  48700. }
  48701. if (value) {
  48702. this._framingBehavior = new BABYLON.FramingBehavior();
  48703. this.addBehavior(this._framingBehavior);
  48704. }
  48705. else if (this._framingBehavior) {
  48706. this.removeBehavior(this._framingBehavior);
  48707. this._framingBehavior = null;
  48708. }
  48709. },
  48710. enumerable: true,
  48711. configurable: true
  48712. });
  48713. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48714. /**
  48715. * Gets the auto rotation behavior of the camera if it has been enabled.
  48716. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48717. */
  48718. get: function () {
  48719. return this._autoRotationBehavior;
  48720. },
  48721. enumerable: true,
  48722. configurable: true
  48723. });
  48724. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48725. /**
  48726. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48727. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48728. */
  48729. get: function () {
  48730. return this._autoRotationBehavior != null;
  48731. },
  48732. set: function (value) {
  48733. if (value === this.useAutoRotationBehavior) {
  48734. return;
  48735. }
  48736. if (value) {
  48737. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48738. this.addBehavior(this._autoRotationBehavior);
  48739. }
  48740. else if (this._autoRotationBehavior) {
  48741. this.removeBehavior(this._autoRotationBehavior);
  48742. this._autoRotationBehavior = null;
  48743. }
  48744. },
  48745. enumerable: true,
  48746. configurable: true
  48747. });
  48748. // Cache
  48749. /** @hidden */
  48750. ArcRotateCamera.prototype._initCache = function () {
  48751. _super.prototype._initCache.call(this);
  48752. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48753. this._cache.alpha = undefined;
  48754. this._cache.beta = undefined;
  48755. this._cache.radius = undefined;
  48756. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48757. };
  48758. /** @hidden */
  48759. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48760. if (!ignoreParentClass) {
  48761. _super.prototype._updateCache.call(this);
  48762. }
  48763. this._cache._target.copyFrom(this._getTargetPosition());
  48764. this._cache.alpha = this.alpha;
  48765. this._cache.beta = this.beta;
  48766. this._cache.radius = this.radius;
  48767. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48768. };
  48769. ArcRotateCamera.prototype._getTargetPosition = function () {
  48770. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48771. var pos = this._targetHost.getAbsolutePosition();
  48772. if (this._targetBoundingCenter) {
  48773. pos.addToRef(this._targetBoundingCenter, this._target);
  48774. }
  48775. else {
  48776. this._target.copyFrom(pos);
  48777. }
  48778. }
  48779. var lockedTargetPosition = this._getLockedTargetPosition();
  48780. if (lockedTargetPosition) {
  48781. return lockedTargetPosition;
  48782. }
  48783. return this._target;
  48784. };
  48785. /**
  48786. * Stores the current state of the camera (alpha, beta, radius and target)
  48787. * @returns the camera itself
  48788. */
  48789. ArcRotateCamera.prototype.storeState = function () {
  48790. this._storedAlpha = this.alpha;
  48791. this._storedBeta = this.beta;
  48792. this._storedRadius = this.radius;
  48793. this._storedTarget = this._getTargetPosition().clone();
  48794. return _super.prototype.storeState.call(this);
  48795. };
  48796. /**
  48797. * @hidden
  48798. * Restored camera state. You must call storeState() first
  48799. */
  48800. ArcRotateCamera.prototype._restoreStateValues = function () {
  48801. if (!_super.prototype._restoreStateValues.call(this)) {
  48802. return false;
  48803. }
  48804. this.alpha = this._storedAlpha;
  48805. this.beta = this._storedBeta;
  48806. this.radius = this._storedRadius;
  48807. this.setTarget(this._storedTarget.clone());
  48808. this.inertialAlphaOffset = 0;
  48809. this.inertialBetaOffset = 0;
  48810. this.inertialRadiusOffset = 0;
  48811. this.inertialPanningX = 0;
  48812. this.inertialPanningY = 0;
  48813. return true;
  48814. };
  48815. // Synchronized
  48816. /** @hidden */
  48817. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48818. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48819. return false;
  48820. return this._cache._target.equals(this._getTargetPosition())
  48821. && this._cache.alpha === this.alpha
  48822. && this._cache.beta === this.beta
  48823. && this._cache.radius === this.radius
  48824. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48825. };
  48826. /**
  48827. * Attached controls to the current camera.
  48828. * @param element Defines the element the controls should be listened from
  48829. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48830. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48831. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48832. */
  48833. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48834. var _this = this;
  48835. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48836. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48837. this._useCtrlForPanning = useCtrlForPanning;
  48838. this._panningMouseButton = panningMouseButton;
  48839. this.inputs.attachElement(element, noPreventDefault);
  48840. this._reset = function () {
  48841. _this.inertialAlphaOffset = 0;
  48842. _this.inertialBetaOffset = 0;
  48843. _this.inertialRadiusOffset = 0;
  48844. _this.inertialPanningX = 0;
  48845. _this.inertialPanningY = 0;
  48846. };
  48847. };
  48848. /**
  48849. * Detach the current controls from the camera.
  48850. * The camera will stop reacting to inputs.
  48851. * @param element Defines the element to stop listening the inputs from
  48852. */
  48853. ArcRotateCamera.prototype.detachControl = function (element) {
  48854. this.inputs.detachElement(element);
  48855. if (this._reset) {
  48856. this._reset();
  48857. }
  48858. };
  48859. /** @hidden */
  48860. ArcRotateCamera.prototype._checkInputs = function () {
  48861. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48862. if (this._collisionTriggered) {
  48863. return;
  48864. }
  48865. this.inputs.checkInputs();
  48866. // Inertia
  48867. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48868. var inertialAlphaOffset = this.inertialAlphaOffset;
  48869. if (this.beta <= 0)
  48870. inertialAlphaOffset *= -1;
  48871. if (this.getScene().useRightHandedSystem)
  48872. inertialAlphaOffset *= -1;
  48873. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48874. inertialAlphaOffset *= -1;
  48875. this.alpha += inertialAlphaOffset;
  48876. this.beta += this.inertialBetaOffset;
  48877. this.radius -= this.inertialRadiusOffset;
  48878. this.inertialAlphaOffset *= this.inertia;
  48879. this.inertialBetaOffset *= this.inertia;
  48880. this.inertialRadiusOffset *= this.inertia;
  48881. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48882. this.inertialAlphaOffset = 0;
  48883. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48884. this.inertialBetaOffset = 0;
  48885. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48886. this.inertialRadiusOffset = 0;
  48887. }
  48888. // Panning inertia
  48889. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48890. if (!this._localDirection) {
  48891. this._localDirection = BABYLON.Vector3.Zero();
  48892. this._transformedDirection = BABYLON.Vector3.Zero();
  48893. }
  48894. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48895. this._localDirection.multiplyInPlace(this.panningAxis);
  48896. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48897. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48898. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48899. if (!this.panningAxis.y) {
  48900. this._transformedDirection.y = 0;
  48901. }
  48902. if (!this._targetHost) {
  48903. if (this.panningDistanceLimit) {
  48904. this._transformedDirection.addInPlace(this._target);
  48905. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48906. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48907. this._target.copyFrom(this._transformedDirection);
  48908. }
  48909. }
  48910. else {
  48911. this._target.addInPlace(this._transformedDirection);
  48912. }
  48913. }
  48914. this.inertialPanningX *= this.panningInertia;
  48915. this.inertialPanningY *= this.panningInertia;
  48916. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48917. this.inertialPanningX = 0;
  48918. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48919. this.inertialPanningY = 0;
  48920. }
  48921. // Limits
  48922. this._checkLimits();
  48923. _super.prototype._checkInputs.call(this);
  48924. };
  48925. ArcRotateCamera.prototype._checkLimits = function () {
  48926. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48927. if (this.allowUpsideDown && this.beta > Math.PI) {
  48928. this.beta = this.beta - (2 * Math.PI);
  48929. }
  48930. }
  48931. else {
  48932. if (this.beta < this.lowerBetaLimit) {
  48933. this.beta = this.lowerBetaLimit;
  48934. }
  48935. }
  48936. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48937. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48938. this.beta = this.beta + (2 * Math.PI);
  48939. }
  48940. }
  48941. else {
  48942. if (this.beta > this.upperBetaLimit) {
  48943. this.beta = this.upperBetaLimit;
  48944. }
  48945. }
  48946. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48947. this.alpha = this.lowerAlphaLimit;
  48948. }
  48949. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48950. this.alpha = this.upperAlphaLimit;
  48951. }
  48952. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48953. this.radius = this.lowerRadiusLimit;
  48954. }
  48955. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48956. this.radius = this.upperRadiusLimit;
  48957. }
  48958. };
  48959. /**
  48960. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48961. */
  48962. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48963. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48964. this.radius = this._computationVector.length();
  48965. if (this.radius === 0) {
  48966. this.radius = 0.0001; // Just to avoid division by zero
  48967. }
  48968. // Alpha
  48969. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48970. if (this._computationVector.z < 0) {
  48971. this.alpha = 2 * Math.PI - this.alpha;
  48972. }
  48973. // Beta
  48974. this.beta = Math.acos(this._computationVector.y / this.radius);
  48975. this._checkLimits();
  48976. };
  48977. /**
  48978. * Use a position to define the current camera related information like aplha, beta and radius
  48979. * @param position Defines the position to set the camera at
  48980. */
  48981. ArcRotateCamera.prototype.setPosition = function (position) {
  48982. if (this.position.equals(position)) {
  48983. return;
  48984. }
  48985. this.position.copyFrom(position);
  48986. this.rebuildAnglesAndRadius();
  48987. };
  48988. /**
  48989. * Defines the target the camera should look at.
  48990. * This will automatically adapt alpha beta and radius to fit within the new target.
  48991. * @param target Defines the new target as a Vector or a mesh
  48992. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48993. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48994. */
  48995. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48996. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48997. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48998. if (target.getBoundingInfo) {
  48999. if (toBoundingCenter) {
  49000. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49001. }
  49002. else {
  49003. this._targetBoundingCenter = null;
  49004. }
  49005. this._targetHost = target;
  49006. this._target = this._getTargetPosition();
  49007. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49008. }
  49009. else {
  49010. var newTarget = target;
  49011. var currentTarget = this._getTargetPosition();
  49012. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49013. return;
  49014. }
  49015. this._targetHost = null;
  49016. this._target = newTarget;
  49017. this._targetBoundingCenter = null;
  49018. this.onMeshTargetChangedObservable.notifyObservers(null);
  49019. }
  49020. this.rebuildAnglesAndRadius();
  49021. };
  49022. /** @hidden */
  49023. ArcRotateCamera.prototype._getViewMatrix = function () {
  49024. // Compute
  49025. var cosa = Math.cos(this.alpha);
  49026. var sina = Math.sin(this.alpha);
  49027. var cosb = Math.cos(this.beta);
  49028. var sinb = Math.sin(this.beta);
  49029. if (sinb === 0) {
  49030. sinb = 0.0001;
  49031. }
  49032. var target = this._getTargetPosition();
  49033. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49034. target.addToRef(this._computationVector, this._newPosition);
  49035. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49036. if (!this._collider) {
  49037. this._collider = new BABYLON.Collider();
  49038. }
  49039. this._collider._radius = this.collisionRadius;
  49040. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49041. this._collisionTriggered = true;
  49042. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49043. }
  49044. else {
  49045. this.position.copyFrom(this._newPosition);
  49046. var up = this.upVector;
  49047. if (this.allowUpsideDown && sinb < 0) {
  49048. up = up.clone();
  49049. up = up.negate();
  49050. }
  49051. this._computeViewMatrix(this.position, target, up);
  49052. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49053. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49054. }
  49055. this._currentTarget = target;
  49056. return this._viewMatrix;
  49057. };
  49058. /**
  49059. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  49060. * @param meshes Defines the mesh to zoom on
  49061. * @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)
  49062. */
  49063. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49064. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49065. meshes = meshes || this.getScene().meshes;
  49066. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49067. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49068. this.radius = distance * this.zoomOnFactor;
  49069. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49070. };
  49071. /**
  49072. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  49073. * The target will be changed but the radius
  49074. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  49075. * @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)
  49076. */
  49077. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49078. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49079. var meshesOrMinMaxVector;
  49080. var distance;
  49081. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49082. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49083. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49084. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49085. }
  49086. else { //minMaxVector and distance
  49087. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49088. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49089. distance = minMaxVectorAndDistance.distance;
  49090. }
  49091. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49092. if (!doNotUpdateMaxZ) {
  49093. this.maxZ = distance * 2;
  49094. }
  49095. };
  49096. /**
  49097. * @override
  49098. * Override Camera.createRigCamera
  49099. */
  49100. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49101. var alphaShift = 0;
  49102. switch (this.cameraRigMode) {
  49103. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49104. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49106. case BABYLON.Camera.RIG_MODE_VR:
  49107. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49108. break;
  49109. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49110. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49111. break;
  49112. }
  49113. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49114. rigCam._cameraRigParams = {};
  49115. return rigCam;
  49116. };
  49117. /**
  49118. * @hidden
  49119. * @override
  49120. * Override Camera._updateRigCameras
  49121. */
  49122. ArcRotateCamera.prototype._updateRigCameras = function () {
  49123. var camLeft = this._rigCameras[0];
  49124. var camRight = this._rigCameras[1];
  49125. camLeft.beta = camRight.beta = this.beta;
  49126. camLeft.radius = camRight.radius = this.radius;
  49127. switch (this.cameraRigMode) {
  49128. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49131. case BABYLON.Camera.RIG_MODE_VR:
  49132. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49133. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49134. break;
  49135. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49136. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49137. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49138. break;
  49139. }
  49140. _super.prototype._updateRigCameras.call(this);
  49141. };
  49142. /**
  49143. * Destroy the camera and release the current resources hold by it.
  49144. */
  49145. ArcRotateCamera.prototype.dispose = function () {
  49146. this.inputs.clear();
  49147. _super.prototype.dispose.call(this);
  49148. };
  49149. /**
  49150. * Gets the current object class name.
  49151. * @return the class name
  49152. */
  49153. ArcRotateCamera.prototype.getClassName = function () {
  49154. return "ArcRotateCamera";
  49155. };
  49156. __decorate([
  49157. BABYLON.serialize()
  49158. ], ArcRotateCamera.prototype, "alpha", void 0);
  49159. __decorate([
  49160. BABYLON.serialize()
  49161. ], ArcRotateCamera.prototype, "beta", void 0);
  49162. __decorate([
  49163. BABYLON.serialize()
  49164. ], ArcRotateCamera.prototype, "radius", void 0);
  49165. __decorate([
  49166. BABYLON.serializeAsVector3("target")
  49167. ], ArcRotateCamera.prototype, "_target", void 0);
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49171. __decorate([
  49172. BABYLON.serialize()
  49173. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49174. __decorate([
  49175. BABYLON.serialize()
  49176. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49177. __decorate([
  49178. BABYLON.serialize()
  49179. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49180. __decorate([
  49181. BABYLON.serialize()
  49182. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49183. __decorate([
  49184. BABYLON.serialize()
  49185. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49186. __decorate([
  49187. BABYLON.serialize()
  49188. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49189. __decorate([
  49190. BABYLON.serialize()
  49191. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49192. __decorate([
  49193. BABYLON.serialize()
  49194. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49195. __decorate([
  49196. BABYLON.serialize()
  49197. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49198. __decorate([
  49199. BABYLON.serialize()
  49200. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49201. __decorate([
  49202. BABYLON.serialize()
  49203. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49204. __decorate([
  49205. BABYLON.serialize()
  49206. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49207. __decorate([
  49208. BABYLON.serializeAsVector3()
  49209. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49210. __decorate([
  49211. BABYLON.serialize()
  49212. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49213. __decorate([
  49214. BABYLON.serialize()
  49215. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49216. __decorate([
  49217. BABYLON.serialize()
  49218. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  49219. __decorate([
  49220. BABYLON.serialize()
  49221. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49222. __decorate([
  49223. BABYLON.serialize()
  49224. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  49225. return ArcRotateCamera;
  49226. }(BABYLON.TargetCamera));
  49227. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49228. })(BABYLON || (BABYLON = {}));
  49229. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49230. var BABYLON;
  49231. (function (BABYLON) {
  49232. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  49233. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  49234. });
  49235. /**
  49236. * The HemisphericLight simulates the ambient environment light,
  49237. * so the passed direction is the light reflection direction, not the incoming direction.
  49238. */
  49239. var HemisphericLight = /** @class */ (function (_super) {
  49240. __extends(HemisphericLight, _super);
  49241. /**
  49242. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49243. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49244. * The HemisphericLight can't cast shadows.
  49245. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49246. * @param name The friendly name of the light
  49247. * @param direction The direction of the light reflection
  49248. * @param scene The scene the light belongs to
  49249. */
  49250. function HemisphericLight(name, direction, scene) {
  49251. var _this = _super.call(this, name, scene) || this;
  49252. /**
  49253. * The groundColor is the light in the opposite direction to the one specified during creation.
  49254. * 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.
  49255. */
  49256. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49257. _this.direction = direction || BABYLON.Vector3.Up();
  49258. return _this;
  49259. }
  49260. HemisphericLight.prototype._buildUniformLayout = function () {
  49261. this._uniformBuffer.addUniform("vLightData", 4);
  49262. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49263. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49264. this._uniformBuffer.addUniform("vLightGround", 3);
  49265. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49266. this._uniformBuffer.addUniform("depthValues", 2);
  49267. this._uniformBuffer.create();
  49268. };
  49269. /**
  49270. * Returns the string "HemisphericLight".
  49271. * @return The class name
  49272. */
  49273. HemisphericLight.prototype.getClassName = function () {
  49274. return "HemisphericLight";
  49275. };
  49276. /**
  49277. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49278. * Returns the updated direction.
  49279. * @param target The target the direction should point to
  49280. * @return The computed direction
  49281. */
  49282. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49283. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49284. return this.direction;
  49285. };
  49286. /**
  49287. * Returns the shadow generator associated to the light.
  49288. * @returns Always null for hemispheric lights because it does not support shadows.
  49289. */
  49290. HemisphericLight.prototype.getShadowGenerator = function () {
  49291. return null;
  49292. };
  49293. /**
  49294. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49295. * @param effect The effect to update
  49296. * @param lightIndex The index of the light in the effect to update
  49297. * @returns The hemispheric light
  49298. */
  49299. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49300. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49301. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49302. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49303. return this;
  49304. };
  49305. /**
  49306. * Computes the world matrix of the node
  49307. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49308. * @param useWasUpdatedFlag defines a reserved property
  49309. * @returns the world matrix
  49310. */
  49311. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49312. if (!this._worldMatrix) {
  49313. this._worldMatrix = BABYLON.Matrix.Identity();
  49314. }
  49315. return this._worldMatrix;
  49316. };
  49317. /**
  49318. * Returns the integer 3.
  49319. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49320. */
  49321. HemisphericLight.prototype.getTypeID = function () {
  49322. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49323. };
  49324. /**
  49325. * Prepares the list of defines specific to the light type.
  49326. * @param defines the list of defines
  49327. * @param lightIndex defines the index of the light for the effect
  49328. */
  49329. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49330. defines["HEMILIGHT" + lightIndex] = true;
  49331. };
  49332. __decorate([
  49333. BABYLON.serializeAsColor3()
  49334. ], HemisphericLight.prototype, "groundColor", void 0);
  49335. __decorate([
  49336. BABYLON.serializeAsVector3()
  49337. ], HemisphericLight.prototype, "direction", void 0);
  49338. return HemisphericLight;
  49339. }(BABYLON.Light));
  49340. BABYLON.HemisphericLight = HemisphericLight;
  49341. })(BABYLON || (BABYLON = {}));
  49342. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49343. var BABYLON;
  49344. (function (BABYLON) {
  49345. /**
  49346. * Base implementation IShadowLight
  49347. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49348. */
  49349. var ShadowLight = /** @class */ (function (_super) {
  49350. __extends(ShadowLight, _super);
  49351. function ShadowLight() {
  49352. var _this = _super !== null && _super.apply(this, arguments) || this;
  49353. _this._needProjectionMatrixCompute = true;
  49354. return _this;
  49355. }
  49356. ShadowLight.prototype._setPosition = function (value) {
  49357. this._position = value;
  49358. };
  49359. Object.defineProperty(ShadowLight.prototype, "position", {
  49360. /**
  49361. * Sets the position the shadow will be casted from. Also use as the light position for both
  49362. * point and spot lights.
  49363. */
  49364. get: function () {
  49365. return this._position;
  49366. },
  49367. /**
  49368. * Sets the position the shadow will be casted from. Also use as the light position for both
  49369. * point and spot lights.
  49370. */
  49371. set: function (value) {
  49372. this._setPosition(value);
  49373. },
  49374. enumerable: true,
  49375. configurable: true
  49376. });
  49377. ShadowLight.prototype._setDirection = function (value) {
  49378. this._direction = value;
  49379. };
  49380. Object.defineProperty(ShadowLight.prototype, "direction", {
  49381. /**
  49382. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49383. * Also use as the light direction on spot and directional lights.
  49384. */
  49385. get: function () {
  49386. return this._direction;
  49387. },
  49388. /**
  49389. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49390. * Also use as the light direction on spot and directional lights.
  49391. */
  49392. set: function (value) {
  49393. this._setDirection(value);
  49394. },
  49395. enumerable: true,
  49396. configurable: true
  49397. });
  49398. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49399. /**
  49400. * Gets the shadow projection clipping minimum z value.
  49401. */
  49402. get: function () {
  49403. return this._shadowMinZ;
  49404. },
  49405. /**
  49406. * Sets the shadow projection clipping minimum z value.
  49407. */
  49408. set: function (value) {
  49409. this._shadowMinZ = value;
  49410. this.forceProjectionMatrixCompute();
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49416. /**
  49417. * Sets the shadow projection clipping maximum z value.
  49418. */
  49419. get: function () {
  49420. return this._shadowMaxZ;
  49421. },
  49422. /**
  49423. * Gets the shadow projection clipping maximum z value.
  49424. */
  49425. set: function (value) {
  49426. this._shadowMaxZ = value;
  49427. this.forceProjectionMatrixCompute();
  49428. },
  49429. enumerable: true,
  49430. configurable: true
  49431. });
  49432. /**
  49433. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49434. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49435. */
  49436. ShadowLight.prototype.computeTransformedInformation = function () {
  49437. if (this.parent && this.parent.getWorldMatrix) {
  49438. if (!this.transformedPosition) {
  49439. this.transformedPosition = BABYLON.Vector3.Zero();
  49440. }
  49441. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49442. // In case the direction is present.
  49443. if (this.direction) {
  49444. if (!this.transformedDirection) {
  49445. this.transformedDirection = BABYLON.Vector3.Zero();
  49446. }
  49447. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49448. }
  49449. return true;
  49450. }
  49451. return false;
  49452. };
  49453. /**
  49454. * Return the depth scale used for the shadow map.
  49455. * @returns the depth scale.
  49456. */
  49457. ShadowLight.prototype.getDepthScale = function () {
  49458. return 50.0;
  49459. };
  49460. /**
  49461. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49462. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49463. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49464. */
  49465. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49466. return this.transformedDirection ? this.transformedDirection : this.direction;
  49467. };
  49468. /**
  49469. * Returns the ShadowLight absolute position in the World.
  49470. * @returns the position vector in world space
  49471. */
  49472. ShadowLight.prototype.getAbsolutePosition = function () {
  49473. return this.transformedPosition ? this.transformedPosition : this.position;
  49474. };
  49475. /**
  49476. * Sets the ShadowLight direction toward the passed target.
  49477. * @param target The point tot target in local space
  49478. * @returns the updated ShadowLight direction
  49479. */
  49480. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49481. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49482. return this.direction;
  49483. };
  49484. /**
  49485. * Returns the light rotation in euler definition.
  49486. * @returns the x y z rotation in local space.
  49487. */
  49488. ShadowLight.prototype.getRotation = function () {
  49489. this.direction.normalize();
  49490. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49491. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49492. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49493. };
  49494. /**
  49495. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49496. * @returns true if a cube texture needs to be use
  49497. */
  49498. ShadowLight.prototype.needCube = function () {
  49499. return false;
  49500. };
  49501. /**
  49502. * Detects if the projection matrix requires to be recomputed this frame.
  49503. * @returns true if it requires to be recomputed otherwise, false.
  49504. */
  49505. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49506. return this._needProjectionMatrixCompute;
  49507. };
  49508. /**
  49509. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49510. */
  49511. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49512. this._needProjectionMatrixCompute = true;
  49513. };
  49514. /** @hidden */
  49515. ShadowLight.prototype._initCache = function () {
  49516. _super.prototype._initCache.call(this);
  49517. this._cache.position = BABYLON.Vector3.Zero();
  49518. };
  49519. /** @hidden */
  49520. ShadowLight.prototype._isSynchronized = function () {
  49521. if (!this._cache.position.equals(this.position))
  49522. return false;
  49523. return true;
  49524. };
  49525. /**
  49526. * Computes the world matrix of the node
  49527. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49528. * @returns the world matrix
  49529. */
  49530. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49531. if (!force && this.isSynchronized()) {
  49532. this._currentRenderId = this.getScene().getRenderId();
  49533. return this._worldMatrix;
  49534. }
  49535. this._updateCache();
  49536. this._cache.position.copyFrom(this.position);
  49537. if (!this._worldMatrix) {
  49538. this._worldMatrix = BABYLON.Matrix.Identity();
  49539. }
  49540. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49541. if (this.parent && this.parent.getWorldMatrix) {
  49542. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49543. this._markSyncedWithParent();
  49544. }
  49545. // Cache the determinant
  49546. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49547. return this._worldMatrix;
  49548. };
  49549. /**
  49550. * Gets the minZ used for shadow according to both the scene and the light.
  49551. * @param activeCamera The camera we are returning the min for
  49552. * @returns the depth min z
  49553. */
  49554. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49555. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49556. };
  49557. /**
  49558. * Gets the maxZ used for shadow according to both the scene and the light.
  49559. * @param activeCamera The camera we are returning the max for
  49560. * @returns the depth max z
  49561. */
  49562. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49563. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49564. };
  49565. /**
  49566. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49567. * @param matrix The materix to updated with the projection information
  49568. * @param viewMatrix The transform matrix of the light
  49569. * @param renderList The list of mesh to render in the map
  49570. * @returns The current light
  49571. */
  49572. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49573. if (this.customProjectionMatrixBuilder) {
  49574. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49575. }
  49576. else {
  49577. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49578. }
  49579. return this;
  49580. };
  49581. __decorate([
  49582. BABYLON.serializeAsVector3()
  49583. ], ShadowLight.prototype, "position", null);
  49584. __decorate([
  49585. BABYLON.serializeAsVector3()
  49586. ], ShadowLight.prototype, "direction", null);
  49587. __decorate([
  49588. BABYLON.serialize()
  49589. ], ShadowLight.prototype, "shadowMinZ", null);
  49590. __decorate([
  49591. BABYLON.serialize()
  49592. ], ShadowLight.prototype, "shadowMaxZ", null);
  49593. return ShadowLight;
  49594. }(BABYLON.Light));
  49595. BABYLON.ShadowLight = ShadowLight;
  49596. })(BABYLON || (BABYLON = {}));
  49597. //# sourceMappingURL=babylon.shadowLight.js.map
  49598. var BABYLON;
  49599. (function (BABYLON) {
  49600. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49601. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49602. });
  49603. /**
  49604. * A point light is a light defined by an unique point in world space.
  49605. * The light is emitted in every direction from this point.
  49606. * A good example of a point light is a standard light bulb.
  49607. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49608. */
  49609. var PointLight = /** @class */ (function (_super) {
  49610. __extends(PointLight, _super);
  49611. /**
  49612. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49613. * A PointLight emits the light in every direction.
  49614. * It can cast shadows.
  49615. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49616. * ```javascript
  49617. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49618. * ```
  49619. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49620. * @param name The light friendly name
  49621. * @param position The position of the point light in the scene
  49622. * @param scene The scene the lights belongs to
  49623. */
  49624. function PointLight(name, position, scene) {
  49625. var _this = _super.call(this, name, scene) || this;
  49626. _this._shadowAngle = Math.PI / 2;
  49627. _this.position = position;
  49628. return _this;
  49629. }
  49630. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49631. /**
  49632. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49633. * This specifies what angle the shadow will use to be created.
  49634. *
  49635. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49636. */
  49637. get: function () {
  49638. return this._shadowAngle;
  49639. },
  49640. /**
  49641. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49642. * This specifies what angle the shadow will use to be created.
  49643. *
  49644. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49645. */
  49646. set: function (value) {
  49647. this._shadowAngle = value;
  49648. this.forceProjectionMatrixCompute();
  49649. },
  49650. enumerable: true,
  49651. configurable: true
  49652. });
  49653. Object.defineProperty(PointLight.prototype, "direction", {
  49654. /**
  49655. * Gets the direction if it has been set.
  49656. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49657. */
  49658. get: function () {
  49659. return this._direction;
  49660. },
  49661. /**
  49662. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49663. */
  49664. set: function (value) {
  49665. var previousNeedCube = this.needCube();
  49666. this._direction = value;
  49667. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49668. this._shadowGenerator.recreateShadowMap();
  49669. }
  49670. },
  49671. enumerable: true,
  49672. configurable: true
  49673. });
  49674. /**
  49675. * Returns the string "PointLight"
  49676. * @returns the class name
  49677. */
  49678. PointLight.prototype.getClassName = function () {
  49679. return "PointLight";
  49680. };
  49681. /**
  49682. * Returns the integer 0.
  49683. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49684. */
  49685. PointLight.prototype.getTypeID = function () {
  49686. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49687. };
  49688. /**
  49689. * Specifies wether or not the shadowmap should be a cube texture.
  49690. * @returns true if the shadowmap needs to be a cube texture.
  49691. */
  49692. PointLight.prototype.needCube = function () {
  49693. return !this.direction;
  49694. };
  49695. /**
  49696. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49697. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49698. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49699. */
  49700. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49701. if (this.direction) {
  49702. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49703. }
  49704. else {
  49705. switch (faceIndex) {
  49706. case 0:
  49707. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49708. case 1:
  49709. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49710. case 2:
  49711. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49712. case 3:
  49713. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49714. case 4:
  49715. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49716. case 5:
  49717. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49718. }
  49719. }
  49720. return BABYLON.Vector3.Zero();
  49721. };
  49722. /**
  49723. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49724. * - fov = PI / 2
  49725. * - aspect ratio : 1.0
  49726. * - z-near and far equal to the active camera minZ and maxZ.
  49727. * Returns the PointLight.
  49728. */
  49729. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49730. var activeCamera = this.getScene().activeCamera;
  49731. if (!activeCamera) {
  49732. return;
  49733. }
  49734. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49735. };
  49736. PointLight.prototype._buildUniformLayout = function () {
  49737. this._uniformBuffer.addUniform("vLightData", 4);
  49738. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49739. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49740. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49741. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49742. this._uniformBuffer.addUniform("depthValues", 2);
  49743. this._uniformBuffer.create();
  49744. };
  49745. /**
  49746. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49747. * @param effect The effect to update
  49748. * @param lightIndex The index of the light in the effect to update
  49749. * @returns The point light
  49750. */
  49751. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49752. if (this.computeTransformedInformation()) {
  49753. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49754. }
  49755. else {
  49756. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49757. }
  49758. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49759. return this;
  49760. };
  49761. /**
  49762. * Prepares the list of defines specific to the light type.
  49763. * @param defines the list of defines
  49764. * @param lightIndex defines the index of the light for the effect
  49765. */
  49766. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49767. defines["POINTLIGHT" + lightIndex] = true;
  49768. };
  49769. __decorate([
  49770. BABYLON.serialize()
  49771. ], PointLight.prototype, "shadowAngle", null);
  49772. return PointLight;
  49773. }(BABYLON.ShadowLight));
  49774. BABYLON.PointLight = PointLight;
  49775. })(BABYLON || (BABYLON = {}));
  49776. //# sourceMappingURL=babylon.pointLight.js.map
  49777. var BABYLON;
  49778. (function (BABYLON) {
  49779. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49780. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49781. });
  49782. /**
  49783. * A directional light is defined by a direction (what a surprise!).
  49784. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49785. * 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.
  49786. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49787. */
  49788. var DirectionalLight = /** @class */ (function (_super) {
  49789. __extends(DirectionalLight, _super);
  49790. /**
  49791. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49792. * The directional light is emitted from everywhere in the given direction.
  49793. * It can cast shadows.
  49794. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49795. * @param name The friendly name of the light
  49796. * @param direction The direction of the light
  49797. * @param scene The scene the light belongs to
  49798. */
  49799. function DirectionalLight(name, direction, scene) {
  49800. var _this = _super.call(this, name, scene) || this;
  49801. _this._shadowFrustumSize = 0;
  49802. _this._shadowOrthoScale = 0.1;
  49803. /**
  49804. * Automatically compute the projection matrix to best fit (including all the casters)
  49805. * on each frame.
  49806. */
  49807. _this.autoUpdateExtends = true;
  49808. // Cache
  49809. _this._orthoLeft = Number.MAX_VALUE;
  49810. _this._orthoRight = Number.MIN_VALUE;
  49811. _this._orthoTop = Number.MIN_VALUE;
  49812. _this._orthoBottom = Number.MAX_VALUE;
  49813. _this.position = direction.scale(-1.0);
  49814. _this.direction = direction;
  49815. return _this;
  49816. }
  49817. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49818. /**
  49819. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49820. */
  49821. get: function () {
  49822. return this._shadowFrustumSize;
  49823. },
  49824. /**
  49825. * Specifies a fix frustum size for the shadow generation.
  49826. */
  49827. set: function (value) {
  49828. this._shadowFrustumSize = value;
  49829. this.forceProjectionMatrixCompute();
  49830. },
  49831. enumerable: true,
  49832. configurable: true
  49833. });
  49834. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49835. /**
  49836. * Gets the shadow projection scale against the optimal computed one.
  49837. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49838. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49839. */
  49840. get: function () {
  49841. return this._shadowOrthoScale;
  49842. },
  49843. /**
  49844. * Sets the shadow projection scale against the optimal computed one.
  49845. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49846. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49847. */
  49848. set: function (value) {
  49849. this._shadowOrthoScale = value;
  49850. this.forceProjectionMatrixCompute();
  49851. },
  49852. enumerable: true,
  49853. configurable: true
  49854. });
  49855. /**
  49856. * Returns the string "DirectionalLight".
  49857. * @return The class name
  49858. */
  49859. DirectionalLight.prototype.getClassName = function () {
  49860. return "DirectionalLight";
  49861. };
  49862. /**
  49863. * Returns the integer 1.
  49864. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49865. */
  49866. DirectionalLight.prototype.getTypeID = function () {
  49867. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49868. };
  49869. /**
  49870. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49871. * Returns the DirectionalLight Shadow projection matrix.
  49872. */
  49873. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49874. if (this.shadowFrustumSize > 0) {
  49875. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49876. }
  49877. else {
  49878. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49879. }
  49880. };
  49881. /**
  49882. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49883. * Returns the DirectionalLight Shadow projection matrix.
  49884. */
  49885. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49886. var activeCamera = this.getScene().activeCamera;
  49887. if (!activeCamera) {
  49888. return;
  49889. }
  49890. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49891. };
  49892. /**
  49893. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49894. * Returns the DirectionalLight Shadow projection matrix.
  49895. */
  49896. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49897. var activeCamera = this.getScene().activeCamera;
  49898. if (!activeCamera) {
  49899. return;
  49900. }
  49901. // Check extends
  49902. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49903. var tempVector3 = BABYLON.Vector3.Zero();
  49904. this._orthoLeft = Number.MAX_VALUE;
  49905. this._orthoRight = Number.MIN_VALUE;
  49906. this._orthoTop = Number.MIN_VALUE;
  49907. this._orthoBottom = Number.MAX_VALUE;
  49908. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49909. var mesh = renderList[meshIndex];
  49910. if (!mesh) {
  49911. continue;
  49912. }
  49913. var boundingInfo = mesh.getBoundingInfo();
  49914. var boundingBox = boundingInfo.boundingBox;
  49915. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49916. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49917. if (tempVector3.x < this._orthoLeft)
  49918. this._orthoLeft = tempVector3.x;
  49919. if (tempVector3.y < this._orthoBottom)
  49920. this._orthoBottom = tempVector3.y;
  49921. if (tempVector3.x > this._orthoRight)
  49922. this._orthoRight = tempVector3.x;
  49923. if (tempVector3.y > this._orthoTop)
  49924. this._orthoTop = tempVector3.y;
  49925. }
  49926. }
  49927. }
  49928. var xOffset = this._orthoRight - this._orthoLeft;
  49929. var yOffset = this._orthoTop - this._orthoBottom;
  49930. 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);
  49931. };
  49932. DirectionalLight.prototype._buildUniformLayout = function () {
  49933. this._uniformBuffer.addUniform("vLightData", 4);
  49934. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49935. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49936. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49937. this._uniformBuffer.addUniform("depthValues", 2);
  49938. this._uniformBuffer.create();
  49939. };
  49940. /**
  49941. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49942. * @param effect The effect to update
  49943. * @param lightIndex The index of the light in the effect to update
  49944. * @returns The directional light
  49945. */
  49946. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49947. if (this.computeTransformedInformation()) {
  49948. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49949. return this;
  49950. }
  49951. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49952. return this;
  49953. };
  49954. /**
  49955. * Gets the minZ used for shadow according to both the scene and the light.
  49956. *
  49957. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49958. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49959. * @param activeCamera The camera we are returning the min for
  49960. * @returns the depth min z
  49961. */
  49962. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49963. return 1;
  49964. };
  49965. /**
  49966. * Gets the maxZ used for shadow according to both the scene and the light.
  49967. *
  49968. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49969. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49970. * @param activeCamera The camera we are returning the max for
  49971. * @returns the depth max z
  49972. */
  49973. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49974. return 1;
  49975. };
  49976. /**
  49977. * Prepares the list of defines specific to the light type.
  49978. * @param defines the list of defines
  49979. * @param lightIndex defines the index of the light for the effect
  49980. */
  49981. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49982. defines["DIRLIGHT" + lightIndex] = true;
  49983. };
  49984. __decorate([
  49985. BABYLON.serialize()
  49986. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49987. __decorate([
  49988. BABYLON.serialize()
  49989. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49990. __decorate([
  49991. BABYLON.serialize()
  49992. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49993. return DirectionalLight;
  49994. }(BABYLON.ShadowLight));
  49995. BABYLON.DirectionalLight = DirectionalLight;
  49996. })(BABYLON || (BABYLON = {}));
  49997. //# sourceMappingURL=babylon.directionalLight.js.map
  49998. var BABYLON;
  49999. (function (BABYLON) {
  50000. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50001. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50002. });
  50003. /**
  50004. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50005. * These values define a cone of light starting from the position, emitting toward the direction.
  50006. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50007. * and the exponent defines the speed of the decay of the light with distance (reach).
  50008. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50009. */
  50010. var SpotLight = /** @class */ (function (_super) {
  50011. __extends(SpotLight, _super);
  50012. /**
  50013. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50014. * It can cast shadows.
  50015. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50016. * @param name The light friendly name
  50017. * @param position The position of the spot light in the scene
  50018. * @param direction The direction of the light in the scene
  50019. * @param angle The cone angle of the light in Radians
  50020. * @param exponent The light decay speed with the distance from the emission spot
  50021. * @param scene The scene the lights belongs to
  50022. */
  50023. function SpotLight(name, position, direction, angle, exponent, scene) {
  50024. var _this = _super.call(this, name, scene) || this;
  50025. _this._innerAngle = 0;
  50026. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50027. _this._projectionTextureLightNear = 1e-6;
  50028. _this._projectionTextureLightFar = 1000.0;
  50029. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50030. _this._projectionTextureViewLightDirty = true;
  50031. _this._projectionTextureProjectionLightDirty = true;
  50032. _this._projectionTextureDirty = true;
  50033. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50034. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50035. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50036. _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);
  50037. _this.position = position;
  50038. _this.direction = direction;
  50039. _this.angle = angle;
  50040. _this.exponent = exponent;
  50041. return _this;
  50042. }
  50043. Object.defineProperty(SpotLight.prototype, "angle", {
  50044. /**
  50045. * Gets the cone angle of the spot light in Radians.
  50046. */
  50047. get: function () {
  50048. return this._angle;
  50049. },
  50050. /**
  50051. * Sets the cone angle of the spot light in Radians.
  50052. */
  50053. set: function (value) {
  50054. this._angle = value;
  50055. this._cosHalfAngle = Math.cos(value * 0.5);
  50056. this._projectionTextureProjectionLightDirty = true;
  50057. this.forceProjectionMatrixCompute();
  50058. this._computeAngleValues();
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  50064. /**
  50065. * Only used in gltf falloff mode, this defines the angle where
  50066. * the directional falloff will start before cutting at angle which could be seen
  50067. * as outer angle.
  50068. */
  50069. get: function () {
  50070. return this._innerAngle;
  50071. },
  50072. /**
  50073. * Only used in gltf falloff mode, this defines the angle where
  50074. * the directional falloff will start before cutting at angle which could be seen
  50075. * as outer angle.
  50076. */
  50077. set: function (value) {
  50078. this._innerAngle = value;
  50079. this._computeAngleValues();
  50080. },
  50081. enumerable: true,
  50082. configurable: true
  50083. });
  50084. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50085. /**
  50086. * Allows scaling the angle of the light for shadow generation only.
  50087. */
  50088. get: function () {
  50089. return this._shadowAngleScale;
  50090. },
  50091. /**
  50092. * Allows scaling the angle of the light for shadow generation only.
  50093. */
  50094. set: function (value) {
  50095. this._shadowAngleScale = value;
  50096. this.forceProjectionMatrixCompute();
  50097. },
  50098. enumerable: true,
  50099. configurable: true
  50100. });
  50101. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50102. /**
  50103. * Allows reading the projecton texture
  50104. */
  50105. get: function () {
  50106. return this._projectionTextureMatrix;
  50107. },
  50108. enumerable: true,
  50109. configurable: true
  50110. });
  50111. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50112. /**
  50113. * Gets the near clip of the Spotlight for texture projection.
  50114. */
  50115. get: function () {
  50116. return this._projectionTextureLightNear;
  50117. },
  50118. /**
  50119. * Sets the near clip of the Spotlight for texture projection.
  50120. */
  50121. set: function (value) {
  50122. this._projectionTextureLightNear = value;
  50123. this._projectionTextureProjectionLightDirty = true;
  50124. },
  50125. enumerable: true,
  50126. configurable: true
  50127. });
  50128. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50129. /**
  50130. * Gets the far clip of the Spotlight for texture projection.
  50131. */
  50132. get: function () {
  50133. return this._projectionTextureLightFar;
  50134. },
  50135. /**
  50136. * Sets the far clip of the Spotlight for texture projection.
  50137. */
  50138. set: function (value) {
  50139. this._projectionTextureLightFar = value;
  50140. this._projectionTextureProjectionLightDirty = true;
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50146. /**
  50147. * Gets the Up vector of the Spotlight for texture projection.
  50148. */
  50149. get: function () {
  50150. return this._projectionTextureUpDirection;
  50151. },
  50152. /**
  50153. * Sets the Up vector of the Spotlight for texture projection.
  50154. */
  50155. set: function (value) {
  50156. this._projectionTextureUpDirection = value;
  50157. this._projectionTextureProjectionLightDirty = true;
  50158. },
  50159. enumerable: true,
  50160. configurable: true
  50161. });
  50162. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50163. /**
  50164. * Gets the projection texture of the light.
  50165. */
  50166. get: function () {
  50167. return this._projectionTexture;
  50168. },
  50169. /**
  50170. * Sets the projection texture of the light.
  50171. */
  50172. set: function (value) {
  50173. this._projectionTexture = value;
  50174. this._projectionTextureDirty = true;
  50175. },
  50176. enumerable: true,
  50177. configurable: true
  50178. });
  50179. /**
  50180. * Returns the string "SpotLight".
  50181. * @returns the class name
  50182. */
  50183. SpotLight.prototype.getClassName = function () {
  50184. return "SpotLight";
  50185. };
  50186. /**
  50187. * Returns the integer 2.
  50188. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50189. */
  50190. SpotLight.prototype.getTypeID = function () {
  50191. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50192. };
  50193. /**
  50194. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50195. */
  50196. SpotLight.prototype._setDirection = function (value) {
  50197. _super.prototype._setDirection.call(this, value);
  50198. this._projectionTextureViewLightDirty = true;
  50199. };
  50200. /**
  50201. * Overrides the position setter to recompute the projection texture view light Matrix.
  50202. */
  50203. SpotLight.prototype._setPosition = function (value) {
  50204. _super.prototype._setPosition.call(this, value);
  50205. this._projectionTextureViewLightDirty = true;
  50206. };
  50207. /**
  50208. * 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.
  50209. * Returns the SpotLight.
  50210. */
  50211. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50212. var activeCamera = this.getScene().activeCamera;
  50213. if (!activeCamera) {
  50214. return;
  50215. }
  50216. this._shadowAngleScale = this._shadowAngleScale || 1;
  50217. var angle = this._shadowAngleScale * this._angle;
  50218. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50219. };
  50220. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50221. this._projectionTextureViewLightDirty = false;
  50222. this._projectionTextureDirty = true;
  50223. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50224. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50225. };
  50226. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50227. this._projectionTextureProjectionLightDirty = false;
  50228. this._projectionTextureDirty = true;
  50229. var light_far = this.projectionTextureLightFar;
  50230. var light_near = this.projectionTextureLightNear;
  50231. var P = light_far / (light_far - light_near);
  50232. var Q = -P * light_near;
  50233. var S = 1.0 / Math.tan(this._angle / 2.0);
  50234. var A = 1.0;
  50235. 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);
  50236. };
  50237. /**
  50238. * Main function for light texture projection matrix computing.
  50239. */
  50240. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50241. this._projectionTextureDirty = false;
  50242. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50243. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50244. };
  50245. SpotLight.prototype._buildUniformLayout = function () {
  50246. this._uniformBuffer.addUniform("vLightData", 4);
  50247. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50248. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50249. this._uniformBuffer.addUniform("vLightDirection", 3);
  50250. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50251. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50252. this._uniformBuffer.addUniform("depthValues", 2);
  50253. this._uniformBuffer.create();
  50254. };
  50255. SpotLight.prototype._computeAngleValues = function () {
  50256. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50257. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50258. };
  50259. /**
  50260. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50261. * @param effect The effect to update
  50262. * @param lightIndex The index of the light in the effect to update
  50263. * @returns The spot light
  50264. */
  50265. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50266. var normalizeDirection;
  50267. if (this.computeTransformedInformation()) {
  50268. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50269. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50270. }
  50271. else {
  50272. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50273. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50274. }
  50275. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50276. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50277. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50278. if (this._projectionTextureViewLightDirty) {
  50279. this._computeProjectionTextureViewLightMatrix();
  50280. }
  50281. if (this._projectionTextureProjectionLightDirty) {
  50282. this._computeProjectionTextureProjectionLightMatrix();
  50283. }
  50284. if (this._projectionTextureDirty) {
  50285. this._computeProjectionTextureMatrix();
  50286. }
  50287. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50288. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50289. }
  50290. return this;
  50291. };
  50292. /**
  50293. * Disposes the light and the associated resources.
  50294. */
  50295. SpotLight.prototype.dispose = function () {
  50296. _super.prototype.dispose.call(this);
  50297. if (this._projectionTexture) {
  50298. this._projectionTexture.dispose();
  50299. }
  50300. };
  50301. /**
  50302. * Prepares the list of defines specific to the light type.
  50303. * @param defines the list of defines
  50304. * @param lightIndex defines the index of the light for the effect
  50305. */
  50306. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50307. defines["SPOTLIGHT" + lightIndex] = true;
  50308. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50309. };
  50310. __decorate([
  50311. BABYLON.serialize()
  50312. ], SpotLight.prototype, "angle", null);
  50313. __decorate([
  50314. BABYLON.serialize()
  50315. ], SpotLight.prototype, "innerAngle", null);
  50316. __decorate([
  50317. BABYLON.serialize()
  50318. ], SpotLight.prototype, "shadowAngleScale", null);
  50319. __decorate([
  50320. BABYLON.serialize()
  50321. ], SpotLight.prototype, "exponent", void 0);
  50322. __decorate([
  50323. BABYLON.serialize()
  50324. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50325. __decorate([
  50326. BABYLON.serialize()
  50327. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50328. __decorate([
  50329. BABYLON.serialize()
  50330. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50331. __decorate([
  50332. BABYLON.serializeAsTexture("projectedLightTexture")
  50333. ], SpotLight.prototype, "_projectionTexture", void 0);
  50334. return SpotLight;
  50335. }(BABYLON.ShadowLight));
  50336. BABYLON.SpotLight = SpotLight;
  50337. })(BABYLON || (BABYLON = {}));
  50338. //# sourceMappingURL=babylon.spotLight.js.map
  50339. var BABYLON;
  50340. (function (BABYLON) {
  50341. /**
  50342. * Class used to override all child animations of a given target
  50343. */
  50344. var AnimationPropertiesOverride = /** @class */ (function () {
  50345. function AnimationPropertiesOverride() {
  50346. /**
  50347. * Gets or sets a value indicating if animation blending must be used
  50348. */
  50349. this.enableBlending = false;
  50350. /**
  50351. * Gets or sets the blending speed to use when enableBlending is true
  50352. */
  50353. this.blendingSpeed = 0.01;
  50354. /**
  50355. * Gets or sets the default loop mode to use
  50356. */
  50357. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50358. }
  50359. return AnimationPropertiesOverride;
  50360. }());
  50361. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50362. })(BABYLON || (BABYLON = {}));
  50363. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50364. var BABYLON;
  50365. (function (BABYLON) {
  50366. /**
  50367. * Represents the range of an animation
  50368. */
  50369. var AnimationRange = /** @class */ (function () {
  50370. /**
  50371. * Initializes the range of an animation
  50372. * @param name The name of the animation range
  50373. * @param from The starting frame of the animation
  50374. * @param to The ending frame of the animation
  50375. */
  50376. function AnimationRange(
  50377. /**The name of the animation range**/
  50378. name,
  50379. /**The starting frame of the animation */
  50380. from,
  50381. /**The ending frame of the animation*/
  50382. to) {
  50383. this.name = name;
  50384. this.from = from;
  50385. this.to = to;
  50386. }
  50387. /**
  50388. * Makes a copy of the animation range
  50389. * @returns A copy of the animation range
  50390. */
  50391. AnimationRange.prototype.clone = function () {
  50392. return new AnimationRange(this.name, this.from, this.to);
  50393. };
  50394. return AnimationRange;
  50395. }());
  50396. BABYLON.AnimationRange = AnimationRange;
  50397. /**
  50398. * Composed of a frame, and an action function
  50399. */
  50400. var AnimationEvent = /** @class */ (function () {
  50401. /**
  50402. * Initializes the animation event
  50403. * @param frame The frame for which the event is triggered
  50404. * @param action The event to perform when triggered
  50405. * @param onlyOnce Specifies if the event should be triggered only once
  50406. */
  50407. function AnimationEvent(
  50408. /** The frame for which the event is triggered **/
  50409. frame,
  50410. /** The event to perform when triggered **/
  50411. action,
  50412. /** Specifies if the event should be triggered only once**/
  50413. onlyOnce) {
  50414. this.frame = frame;
  50415. this.action = action;
  50416. this.onlyOnce = onlyOnce;
  50417. /**
  50418. * Specifies if the animation event is done
  50419. */
  50420. this.isDone = false;
  50421. }
  50422. /** @hidden */
  50423. AnimationEvent.prototype._clone = function () {
  50424. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50425. };
  50426. return AnimationEvent;
  50427. }());
  50428. BABYLON.AnimationEvent = AnimationEvent;
  50429. /**
  50430. * A cursor which tracks a point on a path
  50431. */
  50432. var PathCursor = /** @class */ (function () {
  50433. /**
  50434. * Initializes the path cursor
  50435. * @param path The path to track
  50436. */
  50437. function PathCursor(path) {
  50438. this.path = path;
  50439. /**
  50440. * Stores path cursor callbacks for when an onchange event is triggered
  50441. */
  50442. this._onchange = new Array();
  50443. /**
  50444. * The value of the path cursor
  50445. */
  50446. this.value = 0;
  50447. /**
  50448. * The animation array of the path cursor
  50449. */
  50450. this.animations = new Array();
  50451. }
  50452. /**
  50453. * Gets the cursor point on the path
  50454. * @returns A point on the path cursor at the cursor location
  50455. */
  50456. PathCursor.prototype.getPoint = function () {
  50457. var point = this.path.getPointAtLengthPosition(this.value);
  50458. return new BABYLON.Vector3(point.x, 0, point.y);
  50459. };
  50460. /**
  50461. * Moves the cursor ahead by the step amount
  50462. * @param step The amount to move the cursor forward
  50463. * @returns This path cursor
  50464. */
  50465. PathCursor.prototype.moveAhead = function (step) {
  50466. if (step === void 0) { step = 0.002; }
  50467. this.move(step);
  50468. return this;
  50469. };
  50470. /**
  50471. * Moves the cursor behind by the step amount
  50472. * @param step The amount to move the cursor back
  50473. * @returns This path cursor
  50474. */
  50475. PathCursor.prototype.moveBack = function (step) {
  50476. if (step === void 0) { step = 0.002; }
  50477. this.move(-step);
  50478. return this;
  50479. };
  50480. /**
  50481. * Moves the cursor by the step amount
  50482. * If the step amount is greater than one, an exception is thrown
  50483. * @param step The amount to move the cursor
  50484. * @returns This path cursor
  50485. */
  50486. PathCursor.prototype.move = function (step) {
  50487. if (Math.abs(step) > 1) {
  50488. throw "step size should be less than 1.";
  50489. }
  50490. this.value += step;
  50491. this.ensureLimits();
  50492. this.raiseOnChange();
  50493. return this;
  50494. };
  50495. /**
  50496. * Ensures that the value is limited between zero and one
  50497. * @returns This path cursor
  50498. */
  50499. PathCursor.prototype.ensureLimits = function () {
  50500. while (this.value > 1) {
  50501. this.value -= 1;
  50502. }
  50503. while (this.value < 0) {
  50504. this.value += 1;
  50505. }
  50506. return this;
  50507. };
  50508. /**
  50509. * Runs onchange callbacks on change (used by the animation engine)
  50510. * @returns This path cursor
  50511. */
  50512. PathCursor.prototype.raiseOnChange = function () {
  50513. var _this = this;
  50514. this._onchange.forEach(function (f) { return f(_this); });
  50515. return this;
  50516. };
  50517. /**
  50518. * Executes a function on change
  50519. * @param f A path cursor onchange callback
  50520. * @returns This path cursor
  50521. */
  50522. PathCursor.prototype.onchange = function (f) {
  50523. this._onchange.push(f);
  50524. return this;
  50525. };
  50526. return PathCursor;
  50527. }());
  50528. BABYLON.PathCursor = PathCursor;
  50529. /**
  50530. * Enum for the animation key frame interpolation type
  50531. */
  50532. var AnimationKeyInterpolation;
  50533. (function (AnimationKeyInterpolation) {
  50534. /**
  50535. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50536. */
  50537. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50538. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50539. /**
  50540. * Class used to store any kind of animation
  50541. */
  50542. var Animation = /** @class */ (function () {
  50543. /**
  50544. * Initializes the animation
  50545. * @param name Name of the animation
  50546. * @param targetProperty Property to animate
  50547. * @param framePerSecond The frames per second of the animation
  50548. * @param dataType The data type of the animation
  50549. * @param loopMode The loop mode of the animation
  50550. * @param enableBlendings Specifies if blending should be enabled
  50551. */
  50552. function Animation(
  50553. /**Name of the animation */
  50554. name,
  50555. /**Property to animate */
  50556. targetProperty,
  50557. /**The frames per second of the animation */
  50558. framePerSecond,
  50559. /**The data type of the animation */
  50560. dataType,
  50561. /**The loop mode of the animation */
  50562. loopMode,
  50563. /**Specifies if blending should be enabled */
  50564. enableBlending) {
  50565. this.name = name;
  50566. this.targetProperty = targetProperty;
  50567. this.framePerSecond = framePerSecond;
  50568. this.dataType = dataType;
  50569. this.loopMode = loopMode;
  50570. this.enableBlending = enableBlending;
  50571. /**
  50572. * @hidden Internal use only
  50573. */
  50574. this._runtimeAnimations = new Array();
  50575. /**
  50576. * The set of event that will be linked to this animation
  50577. */
  50578. this._events = new Array();
  50579. /**
  50580. * Stores the blending speed of the animation
  50581. */
  50582. this.blendingSpeed = 0.01;
  50583. /**
  50584. * Stores the animation ranges for the animation
  50585. */
  50586. this._ranges = {};
  50587. this.targetPropertyPath = targetProperty.split(".");
  50588. this.dataType = dataType;
  50589. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50590. }
  50591. /**
  50592. * @hidden Internal use
  50593. */
  50594. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50595. var dataType = undefined;
  50596. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50597. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50598. }
  50599. else if (from instanceof BABYLON.Quaternion) {
  50600. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50601. }
  50602. else if (from instanceof BABYLON.Vector3) {
  50603. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50604. }
  50605. else if (from instanceof BABYLON.Vector2) {
  50606. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50607. }
  50608. else if (from instanceof BABYLON.Color3) {
  50609. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50610. }
  50611. else if (from instanceof BABYLON.Size) {
  50612. dataType = Animation.ANIMATIONTYPE_SIZE;
  50613. }
  50614. if (dataType == undefined) {
  50615. return null;
  50616. }
  50617. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50618. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50619. animation.setKeys(keys);
  50620. if (easingFunction !== undefined) {
  50621. animation.setEasingFunction(easingFunction);
  50622. }
  50623. return animation;
  50624. };
  50625. /**
  50626. * Sets up an animation
  50627. * @param property The property to animate
  50628. * @param animationType The animation type to apply
  50629. * @param framePerSecond The frames per second of the animation
  50630. * @param easingFunction The easing function used in the animation
  50631. * @returns The created animation
  50632. */
  50633. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50634. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50635. animation.setEasingFunction(easingFunction);
  50636. return animation;
  50637. };
  50638. /**
  50639. * Create and start an animation on a node
  50640. * @param name defines the name of the global animation that will be run on all nodes
  50641. * @param node defines the root node where the animation will take place
  50642. * @param targetProperty defines property to animate
  50643. * @param framePerSecond defines the number of frame per second yo use
  50644. * @param totalFrame defines the number of frames in total
  50645. * @param from defines the initial value
  50646. * @param to defines the final value
  50647. * @param loopMode defines which loop mode you want to use (off by default)
  50648. * @param easingFunction defines the easing function to use (linear by default)
  50649. * @param onAnimationEnd defines the callback to call when animation end
  50650. * @returns the animatable created for this animation
  50651. */
  50652. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50653. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50654. if (!animation) {
  50655. return null;
  50656. }
  50657. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50658. };
  50659. /**
  50660. * Create and start an animation on a node and its descendants
  50661. * @param name defines the name of the global animation that will be run on all nodes
  50662. * @param node defines the root node where the animation will take place
  50663. * @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
  50664. * @param targetProperty defines property to animate
  50665. * @param framePerSecond defines the number of frame per second to use
  50666. * @param totalFrame defines the number of frames in total
  50667. * @param from defines the initial value
  50668. * @param to defines the final value
  50669. * @param loopMode defines which loop mode you want to use (off by default)
  50670. * @param easingFunction defines the easing function to use (linear by default)
  50671. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50672. * @returns the list of animatables created for all nodes
  50673. * @example https://www.babylonjs-playground.com/#MH0VLI
  50674. */
  50675. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50676. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50677. if (!animation) {
  50678. return null;
  50679. }
  50680. var scene = node.getScene();
  50681. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50682. };
  50683. /**
  50684. * Creates a new animation, merges it with the existing animations and starts it
  50685. * @param name Name of the animation
  50686. * @param node Node which contains the scene that begins the animations
  50687. * @param targetProperty Specifies which property to animate
  50688. * @param framePerSecond The frames per second of the animation
  50689. * @param totalFrame The total number of frames
  50690. * @param from The frame at the beginning of the animation
  50691. * @param to The frame at the end of the animation
  50692. * @param loopMode Specifies the loop mode of the animation
  50693. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50694. * @param onAnimationEnd Callback to run once the animation is complete
  50695. * @returns Nullable animation
  50696. */
  50697. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50698. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50699. if (!animation) {
  50700. return null;
  50701. }
  50702. node.animations.push(animation);
  50703. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50704. };
  50705. /**
  50706. * Transition property of an host to the target Value
  50707. * @param property The property to transition
  50708. * @param targetValue The target Value of the property
  50709. * @param host The object where the property to animate belongs
  50710. * @param scene Scene used to run the animation
  50711. * @param frameRate Framerate (in frame/s) to use
  50712. * @param transition The transition type we want to use
  50713. * @param duration The duration of the animation, in milliseconds
  50714. * @param onAnimationEnd Callback trigger at the end of the animation
  50715. * @returns Nullable animation
  50716. */
  50717. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50718. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50719. if (duration <= 0) {
  50720. host[property] = targetValue;
  50721. if (onAnimationEnd) {
  50722. onAnimationEnd();
  50723. }
  50724. return null;
  50725. }
  50726. var endFrame = frameRate * (duration / 1000);
  50727. transition.setKeys([{
  50728. frame: 0,
  50729. value: host[property].clone ? host[property].clone() : host[property]
  50730. },
  50731. {
  50732. frame: endFrame,
  50733. value: targetValue
  50734. }]);
  50735. if (!host.animations) {
  50736. host.animations = [];
  50737. }
  50738. host.animations.push(transition);
  50739. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50740. animation.onAnimationEnd = onAnimationEnd;
  50741. return animation;
  50742. };
  50743. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50744. /**
  50745. * Return the array of runtime animations currently using this animation
  50746. */
  50747. get: function () {
  50748. return this._runtimeAnimations;
  50749. },
  50750. enumerable: true,
  50751. configurable: true
  50752. });
  50753. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50754. /**
  50755. * Specifies if any of the runtime animations are currently running
  50756. */
  50757. get: function () {
  50758. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50759. var runtimeAnimation = _a[_i];
  50760. if (!runtimeAnimation.isStopped) {
  50761. return true;
  50762. }
  50763. }
  50764. return false;
  50765. },
  50766. enumerable: true,
  50767. configurable: true
  50768. });
  50769. // Methods
  50770. /**
  50771. * Converts the animation to a string
  50772. * @param fullDetails support for multiple levels of logging within scene loading
  50773. * @returns String form of the animation
  50774. */
  50775. Animation.prototype.toString = function (fullDetails) {
  50776. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50777. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50778. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50779. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50780. if (fullDetails) {
  50781. ret += ", Ranges: {";
  50782. var first = true;
  50783. for (var name in this._ranges) {
  50784. if (first) {
  50785. ret += ", ";
  50786. first = false;
  50787. }
  50788. ret += name;
  50789. }
  50790. ret += "}";
  50791. }
  50792. return ret;
  50793. };
  50794. /**
  50795. * Add an event to this animation
  50796. * @param event Event to add
  50797. */
  50798. Animation.prototype.addEvent = function (event) {
  50799. this._events.push(event);
  50800. };
  50801. /**
  50802. * Remove all events found at the given frame
  50803. * @param frame The frame to remove events from
  50804. */
  50805. Animation.prototype.removeEvents = function (frame) {
  50806. for (var index = 0; index < this._events.length; index++) {
  50807. if (this._events[index].frame === frame) {
  50808. this._events.splice(index, 1);
  50809. index--;
  50810. }
  50811. }
  50812. };
  50813. /**
  50814. * Retrieves all the events from the animation
  50815. * @returns Events from the animation
  50816. */
  50817. Animation.prototype.getEvents = function () {
  50818. return this._events;
  50819. };
  50820. /**
  50821. * Creates an animation range
  50822. * @param name Name of the animation range
  50823. * @param from Starting frame of the animation range
  50824. * @param to Ending frame of the animation
  50825. */
  50826. Animation.prototype.createRange = function (name, from, to) {
  50827. // check name not already in use; could happen for bones after serialized
  50828. if (!this._ranges[name]) {
  50829. this._ranges[name] = new AnimationRange(name, from, to);
  50830. }
  50831. };
  50832. /**
  50833. * Deletes an animation range by name
  50834. * @param name Name of the animation range to delete
  50835. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50836. */
  50837. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50838. if (deleteFrames === void 0) { deleteFrames = true; }
  50839. var range = this._ranges[name];
  50840. if (!range) {
  50841. return;
  50842. }
  50843. if (deleteFrames) {
  50844. var from = range.from;
  50845. var to = range.to;
  50846. // this loop MUST go high to low for multiple splices to work
  50847. for (var key = this._keys.length - 1; key >= 0; key--) {
  50848. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50849. this._keys.splice(key, 1);
  50850. }
  50851. }
  50852. }
  50853. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50854. };
  50855. /**
  50856. * Gets the animation range by name, or null if not defined
  50857. * @param name Name of the animation range
  50858. * @returns Nullable animation range
  50859. */
  50860. Animation.prototype.getRange = function (name) {
  50861. return this._ranges[name];
  50862. };
  50863. /**
  50864. * Gets the key frames from the animation
  50865. * @returns The key frames of the animation
  50866. */
  50867. Animation.prototype.getKeys = function () {
  50868. return this._keys;
  50869. };
  50870. /**
  50871. * Gets the highest frame rate of the animation
  50872. * @returns Highest frame rate of the animation
  50873. */
  50874. Animation.prototype.getHighestFrame = function () {
  50875. var ret = 0;
  50876. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50877. if (ret < this._keys[key].frame) {
  50878. ret = this._keys[key].frame;
  50879. }
  50880. }
  50881. return ret;
  50882. };
  50883. /**
  50884. * Gets the easing function of the animation
  50885. * @returns Easing function of the animation
  50886. */
  50887. Animation.prototype.getEasingFunction = function () {
  50888. return this._easingFunction;
  50889. };
  50890. /**
  50891. * Sets the easing function of the animation
  50892. * @param easingFunction A custom mathematical formula for animation
  50893. */
  50894. Animation.prototype.setEasingFunction = function (easingFunction) {
  50895. this._easingFunction = easingFunction;
  50896. };
  50897. /**
  50898. * Interpolates a scalar linearly
  50899. * @param startValue Start value of the animation curve
  50900. * @param endValue End value of the animation curve
  50901. * @param gradient Scalar amount to interpolate
  50902. * @returns Interpolated scalar value
  50903. */
  50904. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50905. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50906. };
  50907. /**
  50908. * Interpolates a scalar cubically
  50909. * @param startValue Start value of the animation curve
  50910. * @param outTangent End tangent of the animation
  50911. * @param endValue End value of the animation curve
  50912. * @param inTangent Start tangent of the animation curve
  50913. * @param gradient Scalar amount to interpolate
  50914. * @returns Interpolated scalar value
  50915. */
  50916. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50917. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50918. };
  50919. /**
  50920. * Interpolates a quaternion using a spherical linear interpolation
  50921. * @param startValue Start value of the animation curve
  50922. * @param endValue End value of the animation curve
  50923. * @param gradient Scalar amount to interpolate
  50924. * @returns Interpolated quaternion value
  50925. */
  50926. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50927. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50928. };
  50929. /**
  50930. * Interpolates a quaternion cubically
  50931. * @param startValue Start value of the animation curve
  50932. * @param outTangent End tangent of the animation curve
  50933. * @param endValue End value of the animation curve
  50934. * @param inTangent Start tangent of the animation curve
  50935. * @param gradient Scalar amount to interpolate
  50936. * @returns Interpolated quaternion value
  50937. */
  50938. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50939. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50940. };
  50941. /**
  50942. * Interpolates a Vector3 linearl
  50943. * @param startValue Start value of the animation curve
  50944. * @param endValue End value of the animation curve
  50945. * @param gradient Scalar amount to interpolate
  50946. * @returns Interpolated scalar value
  50947. */
  50948. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50949. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50950. };
  50951. /**
  50952. * Interpolates a Vector3 cubically
  50953. * @param startValue Start value of the animation curve
  50954. * @param outTangent End tangent of the animation
  50955. * @param endValue End value of the animation curve
  50956. * @param inTangent Start tangent of the animation curve
  50957. * @param gradient Scalar amount to interpolate
  50958. * @returns InterpolatedVector3 value
  50959. */
  50960. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50961. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50962. };
  50963. /**
  50964. * Interpolates a Vector2 linearly
  50965. * @param startValue Start value of the animation curve
  50966. * @param endValue End value of the animation curve
  50967. * @param gradient Scalar amount to interpolate
  50968. * @returns Interpolated Vector2 value
  50969. */
  50970. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50971. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50972. };
  50973. /**
  50974. * Interpolates a Vector2 cubically
  50975. * @param startValue Start value of the animation curve
  50976. * @param outTangent End tangent of the animation
  50977. * @param endValue End value of the animation curve
  50978. * @param inTangent Start tangent of the animation curve
  50979. * @param gradient Scalar amount to interpolate
  50980. * @returns Interpolated Vector2 value
  50981. */
  50982. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50983. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50984. };
  50985. /**
  50986. * Interpolates a size linearly
  50987. * @param startValue Start value of the animation curve
  50988. * @param endValue End value of the animation curve
  50989. * @param gradient Scalar amount to interpolate
  50990. * @returns Interpolated Size value
  50991. */
  50992. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50993. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50994. };
  50995. /**
  50996. * Interpolates a Color3 linearly
  50997. * @param startValue Start value of the animation curve
  50998. * @param endValue End value of the animation curve
  50999. * @param gradient Scalar amount to interpolate
  51000. * @returns Interpolated Color3 value
  51001. */
  51002. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51003. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51004. };
  51005. /**
  51006. * @hidden Internal use only
  51007. */
  51008. Animation.prototype._getKeyValue = function (value) {
  51009. if (typeof value === "function") {
  51010. return value();
  51011. }
  51012. return value;
  51013. };
  51014. /**
  51015. * @hidden Internal use only
  51016. */
  51017. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51018. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51019. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51020. }
  51021. var keys = this.getKeys();
  51022. // Try to get a hash to find the right key
  51023. 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));
  51024. if (keys[startKeyIndex].frame >= currentFrame) {
  51025. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51026. startKeyIndex--;
  51027. }
  51028. }
  51029. for (var key = startKeyIndex; key < keys.length; key++) {
  51030. var endKey = keys[key + 1];
  51031. if (endKey.frame >= currentFrame) {
  51032. var startKey = keys[key];
  51033. var startValue = this._getKeyValue(startKey.value);
  51034. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51035. return startValue;
  51036. }
  51037. var endValue = this._getKeyValue(endKey.value);
  51038. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51039. var frameDelta = endKey.frame - startKey.frame;
  51040. // gradient : percent of currentFrame between the frame inf and the frame sup
  51041. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51042. // check for easingFunction and correction of gradient
  51043. var easingFunction = this.getEasingFunction();
  51044. if (easingFunction != null) {
  51045. gradient = easingFunction.ease(gradient);
  51046. }
  51047. switch (this.dataType) {
  51048. // Float
  51049. case Animation.ANIMATIONTYPE_FLOAT:
  51050. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51051. switch (loopMode) {
  51052. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51053. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51054. return floatValue;
  51055. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51056. return offsetValue * repeatCount + floatValue;
  51057. }
  51058. break;
  51059. // Quaternion
  51060. case Animation.ANIMATIONTYPE_QUATERNION:
  51061. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51062. switch (loopMode) {
  51063. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51064. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51065. return quatValue;
  51066. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51067. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51068. }
  51069. return quatValue;
  51070. // Vector3
  51071. case Animation.ANIMATIONTYPE_VECTOR3:
  51072. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51073. switch (loopMode) {
  51074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51076. return vec3Value;
  51077. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51078. return vec3Value.add(offsetValue.scale(repeatCount));
  51079. }
  51080. // Vector2
  51081. case Animation.ANIMATIONTYPE_VECTOR2:
  51082. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51083. switch (loopMode) {
  51084. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51085. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51086. return vec2Value;
  51087. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51088. return vec2Value.add(offsetValue.scale(repeatCount));
  51089. }
  51090. // Size
  51091. case Animation.ANIMATIONTYPE_SIZE:
  51092. switch (loopMode) {
  51093. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51094. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51095. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51096. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51097. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51098. }
  51099. // Color3
  51100. case Animation.ANIMATIONTYPE_COLOR3:
  51101. switch (loopMode) {
  51102. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51103. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51104. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51105. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51106. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51107. }
  51108. // Matrix
  51109. case Animation.ANIMATIONTYPE_MATRIX:
  51110. switch (loopMode) {
  51111. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51112. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51113. if (Animation.AllowMatricesInterpolation) {
  51114. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51115. }
  51116. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51117. return startValue;
  51118. }
  51119. default:
  51120. break;
  51121. }
  51122. break;
  51123. }
  51124. }
  51125. return this._getKeyValue(keys[keys.length - 1].value);
  51126. };
  51127. /**
  51128. * Defines the function to use to interpolate matrices
  51129. * @param startValue defines the start matrix
  51130. * @param endValue defines the end matrix
  51131. * @param gradient defines the gradient between both matrices
  51132. * @param result defines an optional target matrix where to store the interpolation
  51133. * @returns the interpolated matrix
  51134. */
  51135. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51136. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51137. if (result) {
  51138. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51139. return result;
  51140. }
  51141. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51142. }
  51143. if (result) {
  51144. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51145. return result;
  51146. }
  51147. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51148. };
  51149. /**
  51150. * Makes a copy of the animation
  51151. * @returns Cloned animation
  51152. */
  51153. Animation.prototype.clone = function () {
  51154. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51155. clone.enableBlending = this.enableBlending;
  51156. clone.blendingSpeed = this.blendingSpeed;
  51157. if (this._keys) {
  51158. clone.setKeys(this._keys);
  51159. }
  51160. if (this._ranges) {
  51161. clone._ranges = {};
  51162. for (var name in this._ranges) {
  51163. var range = this._ranges[name];
  51164. if (!range) {
  51165. continue;
  51166. }
  51167. clone._ranges[name] = range.clone();
  51168. }
  51169. }
  51170. return clone;
  51171. };
  51172. /**
  51173. * Sets the key frames of the animation
  51174. * @param values The animation key frames to set
  51175. */
  51176. Animation.prototype.setKeys = function (values) {
  51177. this._keys = values.slice(0);
  51178. };
  51179. /**
  51180. * Serializes the animation to an object
  51181. * @returns Serialized object
  51182. */
  51183. Animation.prototype.serialize = function () {
  51184. var serializationObject = {};
  51185. serializationObject.name = this.name;
  51186. serializationObject.property = this.targetProperty;
  51187. serializationObject.framePerSecond = this.framePerSecond;
  51188. serializationObject.dataType = this.dataType;
  51189. serializationObject.loopBehavior = this.loopMode;
  51190. serializationObject.enableBlending = this.enableBlending;
  51191. serializationObject.blendingSpeed = this.blendingSpeed;
  51192. var dataType = this.dataType;
  51193. serializationObject.keys = [];
  51194. var keys = this.getKeys();
  51195. for (var index = 0; index < keys.length; index++) {
  51196. var animationKey = keys[index];
  51197. var key = {};
  51198. key.frame = animationKey.frame;
  51199. switch (dataType) {
  51200. case Animation.ANIMATIONTYPE_FLOAT:
  51201. key.values = [animationKey.value];
  51202. break;
  51203. case Animation.ANIMATIONTYPE_QUATERNION:
  51204. case Animation.ANIMATIONTYPE_MATRIX:
  51205. case Animation.ANIMATIONTYPE_VECTOR3:
  51206. case Animation.ANIMATIONTYPE_COLOR3:
  51207. key.values = animationKey.value.asArray();
  51208. break;
  51209. }
  51210. serializationObject.keys.push(key);
  51211. }
  51212. serializationObject.ranges = [];
  51213. for (var name in this._ranges) {
  51214. var source = this._ranges[name];
  51215. if (!source) {
  51216. continue;
  51217. }
  51218. var range = {};
  51219. range.name = name;
  51220. range.from = source.from;
  51221. range.to = source.to;
  51222. serializationObject.ranges.push(range);
  51223. }
  51224. return serializationObject;
  51225. };
  51226. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51227. /**
  51228. * Get the float animation type
  51229. */
  51230. get: function () {
  51231. return Animation._ANIMATIONTYPE_FLOAT;
  51232. },
  51233. enumerable: true,
  51234. configurable: true
  51235. });
  51236. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51237. /**
  51238. * Get the Vector3 animation type
  51239. */
  51240. get: function () {
  51241. return Animation._ANIMATIONTYPE_VECTOR3;
  51242. },
  51243. enumerable: true,
  51244. configurable: true
  51245. });
  51246. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51247. /**
  51248. * Get the Vector2 animation type
  51249. */
  51250. get: function () {
  51251. return Animation._ANIMATIONTYPE_VECTOR2;
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51257. /**
  51258. * Get the Size animation type
  51259. */
  51260. get: function () {
  51261. return Animation._ANIMATIONTYPE_SIZE;
  51262. },
  51263. enumerable: true,
  51264. configurable: true
  51265. });
  51266. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51267. /**
  51268. * Get the Quaternion animation type
  51269. */
  51270. get: function () {
  51271. return Animation._ANIMATIONTYPE_QUATERNION;
  51272. },
  51273. enumerable: true,
  51274. configurable: true
  51275. });
  51276. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51277. /**
  51278. * Get the Matrix animation type
  51279. */
  51280. get: function () {
  51281. return Animation._ANIMATIONTYPE_MATRIX;
  51282. },
  51283. enumerable: true,
  51284. configurable: true
  51285. });
  51286. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51287. /**
  51288. * Get the Color3 animation type
  51289. */
  51290. get: function () {
  51291. return Animation._ANIMATIONTYPE_COLOR3;
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51297. /**
  51298. * Get the Relative Loop Mode
  51299. */
  51300. get: function () {
  51301. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51302. },
  51303. enumerable: true,
  51304. configurable: true
  51305. });
  51306. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51307. /**
  51308. * Get the Cycle Loop Mode
  51309. */
  51310. get: function () {
  51311. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51312. },
  51313. enumerable: true,
  51314. configurable: true
  51315. });
  51316. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51317. /**
  51318. * Get the Constant Loop Mode
  51319. */
  51320. get: function () {
  51321. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51322. },
  51323. enumerable: true,
  51324. configurable: true
  51325. });
  51326. /** @hidden */
  51327. Animation._UniversalLerp = function (left, right, amount) {
  51328. var constructor = left.constructor;
  51329. if (constructor.Lerp) { // Lerp supported
  51330. return constructor.Lerp(left, right, amount);
  51331. }
  51332. else if (constructor.Slerp) { // Slerp supported
  51333. return constructor.Slerp(left, right, amount);
  51334. }
  51335. else if (left.toFixed) { // Number
  51336. return left * (1.0 - amount) + amount * right;
  51337. }
  51338. else { // Blending not supported
  51339. return right;
  51340. }
  51341. };
  51342. /**
  51343. * Parses an animation object and creates an animation
  51344. * @param parsedAnimation Parsed animation object
  51345. * @returns Animation object
  51346. */
  51347. Animation.Parse = function (parsedAnimation) {
  51348. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51349. var dataType = parsedAnimation.dataType;
  51350. var keys = [];
  51351. var data;
  51352. var index;
  51353. if (parsedAnimation.enableBlending) {
  51354. animation.enableBlending = parsedAnimation.enableBlending;
  51355. }
  51356. if (parsedAnimation.blendingSpeed) {
  51357. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51358. }
  51359. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51360. var key = parsedAnimation.keys[index];
  51361. var inTangent;
  51362. var outTangent;
  51363. switch (dataType) {
  51364. case Animation.ANIMATIONTYPE_FLOAT:
  51365. data = key.values[0];
  51366. if (key.values.length >= 1) {
  51367. inTangent = key.values[1];
  51368. }
  51369. if (key.values.length >= 2) {
  51370. outTangent = key.values[2];
  51371. }
  51372. break;
  51373. case Animation.ANIMATIONTYPE_QUATERNION:
  51374. data = BABYLON.Quaternion.FromArray(key.values);
  51375. if (key.values.length >= 8) {
  51376. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51377. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51378. inTangent = _inTangent;
  51379. }
  51380. }
  51381. if (key.values.length >= 12) {
  51382. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51383. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51384. outTangent = _outTangent;
  51385. }
  51386. }
  51387. break;
  51388. case Animation.ANIMATIONTYPE_MATRIX:
  51389. data = BABYLON.Matrix.FromArray(key.values);
  51390. break;
  51391. case Animation.ANIMATIONTYPE_COLOR3:
  51392. data = BABYLON.Color3.FromArray(key.values);
  51393. break;
  51394. case Animation.ANIMATIONTYPE_VECTOR3:
  51395. default:
  51396. data = BABYLON.Vector3.FromArray(key.values);
  51397. break;
  51398. }
  51399. var keyData = {};
  51400. keyData.frame = key.frame;
  51401. keyData.value = data;
  51402. if (inTangent != undefined) {
  51403. keyData.inTangent = inTangent;
  51404. }
  51405. if (outTangent != undefined) {
  51406. keyData.outTangent = outTangent;
  51407. }
  51408. keys.push(keyData);
  51409. }
  51410. animation.setKeys(keys);
  51411. if (parsedAnimation.ranges) {
  51412. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51413. data = parsedAnimation.ranges[index];
  51414. animation.createRange(data.name, data.from, data.to);
  51415. }
  51416. }
  51417. return animation;
  51418. };
  51419. /**
  51420. * Appends the serialized animations from the source animations
  51421. * @param source Source containing the animations
  51422. * @param destination Target to store the animations
  51423. */
  51424. Animation.AppendSerializedAnimations = function (source, destination) {
  51425. if (source.animations) {
  51426. destination.animations = [];
  51427. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51428. var animation = source.animations[animationIndex];
  51429. destination.animations.push(animation.serialize());
  51430. }
  51431. }
  51432. };
  51433. /**
  51434. * Use matrix interpolation instead of using direct key value when animating matrices
  51435. */
  51436. Animation.AllowMatricesInterpolation = false;
  51437. /**
  51438. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51439. */
  51440. Animation.AllowMatrixDecomposeForInterpolation = true;
  51441. // Statics
  51442. /**
  51443. * Float animation type
  51444. */
  51445. Animation._ANIMATIONTYPE_FLOAT = 0;
  51446. /**
  51447. * Vector3 animation type
  51448. */
  51449. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51450. /**
  51451. * Quaternion animation type
  51452. */
  51453. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51454. /**
  51455. * Matrix animation type
  51456. */
  51457. Animation._ANIMATIONTYPE_MATRIX = 3;
  51458. /**
  51459. * Color3 animation type
  51460. */
  51461. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51462. /**
  51463. * Vector2 animation type
  51464. */
  51465. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51466. /**
  51467. * Size animation type
  51468. */
  51469. Animation._ANIMATIONTYPE_SIZE = 6;
  51470. /**
  51471. * Relative Loop Mode
  51472. */
  51473. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51474. /**
  51475. * Cycle Loop Mode
  51476. */
  51477. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51478. /**
  51479. * Constant Loop Mode
  51480. */
  51481. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51482. return Animation;
  51483. }());
  51484. BABYLON.Animation = Animation;
  51485. })(BABYLON || (BABYLON = {}));
  51486. //# sourceMappingURL=babylon.animation.js.map
  51487. var BABYLON;
  51488. (function (BABYLON) {
  51489. /**
  51490. * This class defines the direct association between an animation and a target
  51491. */
  51492. var TargetedAnimation = /** @class */ (function () {
  51493. function TargetedAnimation() {
  51494. }
  51495. return TargetedAnimation;
  51496. }());
  51497. BABYLON.TargetedAnimation = TargetedAnimation;
  51498. /**
  51499. * Use this class to create coordinated animations on multiple targets
  51500. */
  51501. var AnimationGroup = /** @class */ (function () {
  51502. /**
  51503. * Instantiates a new Animation Group.
  51504. * This helps managing several animations at once.
  51505. * @see http://doc.babylonjs.com/how_to/group
  51506. * @param name Defines the name of the group
  51507. * @param scene Defines the scene the group belongs to
  51508. */
  51509. function AnimationGroup(
  51510. /** The name of the animation group */
  51511. name, scene) {
  51512. if (scene === void 0) { scene = null; }
  51513. this.name = name;
  51514. this._targetedAnimations = new Array();
  51515. this._animatables = new Array();
  51516. this._from = Number.MAX_VALUE;
  51517. this._to = -Number.MAX_VALUE;
  51518. this._speedRatio = 1;
  51519. /**
  51520. * This observable will notify when one animation have ended.
  51521. */
  51522. this.onAnimationEndObservable = new BABYLON.Observable();
  51523. /**
  51524. * This observable will notify when all animations have ended.
  51525. */
  51526. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51527. /**
  51528. * This observable will notify when all animations have paused.
  51529. */
  51530. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51531. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51532. this._scene.animationGroups.push(this);
  51533. }
  51534. Object.defineProperty(AnimationGroup.prototype, "from", {
  51535. /**
  51536. * Gets the first frame
  51537. */
  51538. get: function () {
  51539. return this._from;
  51540. },
  51541. enumerable: true,
  51542. configurable: true
  51543. });
  51544. Object.defineProperty(AnimationGroup.prototype, "to", {
  51545. /**
  51546. * Gets the last frame
  51547. */
  51548. get: function () {
  51549. return this._to;
  51550. },
  51551. enumerable: true,
  51552. configurable: true
  51553. });
  51554. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51555. /**
  51556. * Define if the animations are started
  51557. */
  51558. get: function () {
  51559. return this._isStarted;
  51560. },
  51561. enumerable: true,
  51562. configurable: true
  51563. });
  51564. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51565. /**
  51566. * Gets or sets the speed ratio to use for all animations
  51567. */
  51568. get: function () {
  51569. return this._speedRatio;
  51570. },
  51571. /**
  51572. * Gets or sets the speed ratio to use for all animations
  51573. */
  51574. set: function (value) {
  51575. if (this._speedRatio === value) {
  51576. return;
  51577. }
  51578. this._speedRatio = value;
  51579. for (var index = 0; index < this._animatables.length; index++) {
  51580. var animatable = this._animatables[index];
  51581. animatable.speedRatio = this._speedRatio;
  51582. }
  51583. },
  51584. enumerable: true,
  51585. configurable: true
  51586. });
  51587. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51588. /**
  51589. * Gets the targeted animations for this animation group
  51590. */
  51591. get: function () {
  51592. return this._targetedAnimations;
  51593. },
  51594. enumerable: true,
  51595. configurable: true
  51596. });
  51597. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51598. /**
  51599. * returning the list of animatables controlled by this animation group.
  51600. */
  51601. get: function () {
  51602. return this._animatables;
  51603. },
  51604. enumerable: true,
  51605. configurable: true
  51606. });
  51607. /**
  51608. * Add an animation (with its target) in the group
  51609. * @param animation defines the animation we want to add
  51610. * @param target defines the target of the animation
  51611. * @returns the {BABYLON.TargetedAnimation} object
  51612. */
  51613. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51614. var targetedAnimation = {
  51615. animation: animation,
  51616. target: target
  51617. };
  51618. var keys = animation.getKeys();
  51619. if (this._from > keys[0].frame) {
  51620. this._from = keys[0].frame;
  51621. }
  51622. if (this._to < keys[keys.length - 1].frame) {
  51623. this._to = keys[keys.length - 1].frame;
  51624. }
  51625. this._targetedAnimations.push(targetedAnimation);
  51626. return targetedAnimation;
  51627. };
  51628. /**
  51629. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51630. * It can add constant keys at begin or end
  51631. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51632. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51633. * @returns the animation group
  51634. */
  51635. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51636. if (beginFrame === void 0) { beginFrame = null; }
  51637. if (endFrame === void 0) { endFrame = null; }
  51638. if (beginFrame == null)
  51639. beginFrame = this._from;
  51640. if (endFrame == null)
  51641. endFrame = this._to;
  51642. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51643. var targetedAnimation = this._targetedAnimations[index];
  51644. var keys = targetedAnimation.animation.getKeys();
  51645. var startKey = keys[0];
  51646. var endKey = keys[keys.length - 1];
  51647. if (startKey.frame > beginFrame) {
  51648. var newKey = {
  51649. frame: beginFrame,
  51650. value: startKey.value,
  51651. inTangent: startKey.inTangent,
  51652. outTangent: startKey.outTangent,
  51653. interpolation: startKey.interpolation
  51654. };
  51655. keys.splice(0, 0, newKey);
  51656. }
  51657. if (endKey.frame < endFrame) {
  51658. var newKey = {
  51659. frame: endFrame,
  51660. value: endKey.value,
  51661. inTangent: endKey.outTangent,
  51662. outTangent: endKey.outTangent,
  51663. interpolation: endKey.interpolation
  51664. };
  51665. keys.push(newKey);
  51666. }
  51667. }
  51668. this._from = beginFrame;
  51669. this._to = endFrame;
  51670. return this;
  51671. };
  51672. /**
  51673. * Start all animations on given targets
  51674. * @param loop defines if animations must loop
  51675. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51676. * @param from defines the from key (optional)
  51677. * @param to defines the to key (optional)
  51678. * @returns the current animation group
  51679. */
  51680. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51681. var _this = this;
  51682. if (loop === void 0) { loop = false; }
  51683. if (speedRatio === void 0) { speedRatio = 1; }
  51684. if (this._isStarted || this._targetedAnimations.length === 0) {
  51685. return this;
  51686. }
  51687. var _loop_1 = function (targetedAnimation) {
  51688. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51689. animatable.onAnimationEnd = function () {
  51690. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51691. _this._checkAnimationGroupEnded(animatable);
  51692. };
  51693. this_1._animatables.push(animatable);
  51694. };
  51695. var this_1 = this;
  51696. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51697. var targetedAnimation = _a[_i];
  51698. _loop_1(targetedAnimation);
  51699. }
  51700. this._speedRatio = speedRatio;
  51701. this._isStarted = true;
  51702. return this;
  51703. };
  51704. /**
  51705. * Pause all animations
  51706. * @returns the animation group
  51707. */
  51708. AnimationGroup.prototype.pause = function () {
  51709. if (!this._isStarted) {
  51710. return this;
  51711. }
  51712. for (var index = 0; index < this._animatables.length; index++) {
  51713. var animatable = this._animatables[index];
  51714. animatable.pause();
  51715. }
  51716. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51717. return this;
  51718. };
  51719. /**
  51720. * Play all animations to initial state
  51721. * This function will start() the animations if they were not started or will restart() them if they were paused
  51722. * @param loop defines if animations must loop
  51723. * @returns the animation group
  51724. */
  51725. AnimationGroup.prototype.play = function (loop) {
  51726. // only if all animatables are ready and exist
  51727. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51728. if (loop !== undefined) {
  51729. for (var index = 0; index < this._animatables.length; index++) {
  51730. var animatable = this._animatables[index];
  51731. animatable.loopAnimation = loop;
  51732. }
  51733. }
  51734. this.restart();
  51735. }
  51736. else {
  51737. this.stop();
  51738. this.start(loop, this._speedRatio);
  51739. }
  51740. return this;
  51741. };
  51742. /**
  51743. * Reset all animations to initial state
  51744. * @returns the animation group
  51745. */
  51746. AnimationGroup.prototype.reset = function () {
  51747. if (!this._isStarted) {
  51748. return this;
  51749. }
  51750. for (var index = 0; index < this._animatables.length; index++) {
  51751. var animatable = this._animatables[index];
  51752. animatable.reset();
  51753. }
  51754. return this;
  51755. };
  51756. /**
  51757. * Restart animations from key 0
  51758. * @returns the animation group
  51759. */
  51760. AnimationGroup.prototype.restart = function () {
  51761. if (!this._isStarted) {
  51762. return this;
  51763. }
  51764. for (var index = 0; index < this._animatables.length; index++) {
  51765. var animatable = this._animatables[index];
  51766. animatable.restart();
  51767. }
  51768. return this;
  51769. };
  51770. /**
  51771. * Stop all animations
  51772. * @returns the animation group
  51773. */
  51774. AnimationGroup.prototype.stop = function () {
  51775. if (!this._isStarted) {
  51776. return this;
  51777. }
  51778. var list = this._animatables.slice();
  51779. for (var index = 0; index < list.length; index++) {
  51780. list[index].stop();
  51781. }
  51782. this._isStarted = false;
  51783. return this;
  51784. };
  51785. /**
  51786. * Set animation weight for all animatables
  51787. * @param weight defines the weight to use
  51788. * @return the animationGroup
  51789. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51790. */
  51791. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51792. for (var index = 0; index < this._animatables.length; index++) {
  51793. var animatable = this._animatables[index];
  51794. animatable.weight = weight;
  51795. }
  51796. return this;
  51797. };
  51798. /**
  51799. * Synchronize and normalize all animatables with a source animatable
  51800. * @param root defines the root animatable to synchronize with
  51801. * @return the animationGroup
  51802. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51803. */
  51804. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51805. for (var index = 0; index < this._animatables.length; index++) {
  51806. var animatable = this._animatables[index];
  51807. animatable.syncWith(root);
  51808. }
  51809. return this;
  51810. };
  51811. /**
  51812. * Goes to a specific frame in this animation group
  51813. * @param frame the frame number to go to
  51814. * @return the animationGroup
  51815. */
  51816. AnimationGroup.prototype.goToFrame = function (frame) {
  51817. if (!this._isStarted) {
  51818. return this;
  51819. }
  51820. for (var index = 0; index < this._animatables.length; index++) {
  51821. var animatable = this._animatables[index];
  51822. animatable.goToFrame(frame);
  51823. }
  51824. return this;
  51825. };
  51826. /**
  51827. * Dispose all associated resources
  51828. */
  51829. AnimationGroup.prototype.dispose = function () {
  51830. this._targetedAnimations = [];
  51831. this._animatables = [];
  51832. var index = this._scene.animationGroups.indexOf(this);
  51833. if (index > -1) {
  51834. this._scene.animationGroups.splice(index, 1);
  51835. }
  51836. };
  51837. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51838. // animatable should be taken out of the array
  51839. var idx = this._animatables.indexOf(animatable);
  51840. if (idx > -1) {
  51841. this._animatables.splice(idx, 1);
  51842. }
  51843. // all animatables were removed? animation group ended!
  51844. if (this._animatables.length === 0) {
  51845. this._isStarted = false;
  51846. this.onAnimationGroupEndObservable.notifyObservers(this);
  51847. }
  51848. };
  51849. // Statics
  51850. /**
  51851. * Returns a new AnimationGroup object parsed from the source provided.
  51852. * @param parsedAnimationGroup defines the source
  51853. * @param scene defines the scene that will receive the animationGroup
  51854. * @returns a new AnimationGroup
  51855. */
  51856. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51857. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51858. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51859. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51860. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51861. var id = targetedAnimation.targetId;
  51862. var targetNode = scene.getNodeByID(id);
  51863. if (targetNode != null)
  51864. animationGroup.addTargetedAnimation(animation, targetNode);
  51865. }
  51866. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51867. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51868. return animationGroup;
  51869. };
  51870. /**
  51871. * Returns the string "AnimationGroup"
  51872. * @returns "AnimationGroup"
  51873. */
  51874. AnimationGroup.prototype.getClassName = function () {
  51875. return "AnimationGroup";
  51876. };
  51877. /**
  51878. * Creates a detailled string about the object
  51879. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51880. * @returns a string representing the object
  51881. */
  51882. AnimationGroup.prototype.toString = function (fullDetails) {
  51883. var ret = "Name: " + this.name;
  51884. ret += ", type: " + this.getClassName();
  51885. if (fullDetails) {
  51886. ret += ", from: " + this._from;
  51887. ret += ", to: " + this._to;
  51888. ret += ", isStarted: " + this._isStarted;
  51889. ret += ", speedRatio: " + this._speedRatio;
  51890. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51891. ret += ", animatables length: " + this._animatables;
  51892. }
  51893. return ret;
  51894. };
  51895. return AnimationGroup;
  51896. }());
  51897. BABYLON.AnimationGroup = AnimationGroup;
  51898. })(BABYLON || (BABYLON = {}));
  51899. //# sourceMappingURL=babylon.animationGroup.js.map
  51900. var BABYLON;
  51901. (function (BABYLON) {
  51902. // Static values to help the garbage collector
  51903. // Quaternion
  51904. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51905. // Vector3
  51906. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51907. // Vector2
  51908. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51909. // Size
  51910. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51911. // Color3
  51912. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51913. /**
  51914. * Defines a runtime animation
  51915. */
  51916. var RuntimeAnimation = /** @class */ (function () {
  51917. /**
  51918. * Create a new RuntimeAnimation object
  51919. * @param target defines the target of the animation
  51920. * @param animation defines the source animation object
  51921. * @param scene defines the hosting scene
  51922. * @param host defines the initiating Animatable
  51923. */
  51924. function RuntimeAnimation(target, animation, scene, host) {
  51925. var _this = this;
  51926. this._events = new Array();
  51927. /**
  51928. * The current frame of the runtime animation
  51929. */
  51930. this._currentFrame = 0;
  51931. /**
  51932. * The original value of the runtime animation
  51933. */
  51934. this._originalValue = new Array();
  51935. /**
  51936. * The offsets cache of the runtime animation
  51937. */
  51938. this._offsetsCache = {};
  51939. /**
  51940. * The high limits cache of the runtime animation
  51941. */
  51942. this._highLimitsCache = {};
  51943. /**
  51944. * Specifies if the runtime animation has been stopped
  51945. */
  51946. this._stopped = false;
  51947. /**
  51948. * The blending factor of the runtime animation
  51949. */
  51950. this._blendingFactor = 0;
  51951. /**
  51952. * The target path of the runtime animation
  51953. */
  51954. this._targetPath = "";
  51955. /**
  51956. * The weight of the runtime animation
  51957. */
  51958. this._weight = 1.0;
  51959. /**
  51960. * The ratio offset of the runtime animation
  51961. */
  51962. this._ratioOffset = 0;
  51963. /**
  51964. * The previous delay of the runtime animation
  51965. */
  51966. this._previousDelay = 0;
  51967. /**
  51968. * The previous ratio of the runtime animation
  51969. */
  51970. this._previousRatio = 0;
  51971. this._animation = animation;
  51972. this._target = target;
  51973. this._scene = scene;
  51974. this._host = host;
  51975. animation._runtimeAnimations.push(this);
  51976. // Cloning events locally
  51977. var events = animation.getEvents();
  51978. if (events && events.length > 0) {
  51979. events.forEach(function (e) {
  51980. _this._events.push(e._clone());
  51981. });
  51982. }
  51983. }
  51984. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51985. /**
  51986. * Gets the current frame of the runtime animation
  51987. */
  51988. get: function () {
  51989. return this._currentFrame;
  51990. },
  51991. enumerable: true,
  51992. configurable: true
  51993. });
  51994. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51995. /**
  51996. * Gets the weight of the runtime animation
  51997. */
  51998. get: function () {
  51999. return this._weight;
  52000. },
  52001. enumerable: true,
  52002. configurable: true
  52003. });
  52004. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52005. /**
  52006. * Gets the current value of the runtime animation
  52007. */
  52008. get: function () {
  52009. return this._currentValue;
  52010. },
  52011. enumerable: true,
  52012. configurable: true
  52013. });
  52014. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52015. /**
  52016. * Gets the target path of the runtime animation
  52017. */
  52018. get: function () {
  52019. return this._targetPath;
  52020. },
  52021. enumerable: true,
  52022. configurable: true
  52023. });
  52024. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52025. /**
  52026. * Gets the actual target of the runtime animation
  52027. */
  52028. get: function () {
  52029. return this._activeTarget;
  52030. },
  52031. enumerable: true,
  52032. configurable: true
  52033. });
  52034. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52035. /**
  52036. * Gets the animation from the runtime animation
  52037. */
  52038. get: function () {
  52039. return this._animation;
  52040. },
  52041. enumerable: true,
  52042. configurable: true
  52043. });
  52044. /**
  52045. * Resets the runtime animation to the beginning
  52046. * @param restoreOriginal defines whether to restore the target property to the original value
  52047. */
  52048. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52049. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52050. if (restoreOriginal) {
  52051. if (this._target instanceof Array) {
  52052. var index = 0;
  52053. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52054. var target = _a[_i];
  52055. if (this._originalValue[index] !== undefined) {
  52056. this._setValue(target, this._originalValue[index], -1);
  52057. }
  52058. index++;
  52059. }
  52060. }
  52061. else {
  52062. if (this._originalValue[0] !== undefined) {
  52063. this._setValue(this._target, this._originalValue[0], -1);
  52064. }
  52065. }
  52066. }
  52067. this._offsetsCache = {};
  52068. this._highLimitsCache = {};
  52069. this._currentFrame = 0;
  52070. this._blendingFactor = 0;
  52071. this._originalValue = new Array();
  52072. // Events
  52073. for (var index = 0; index < this._events.length; index++) {
  52074. this._events[index].isDone = false;
  52075. }
  52076. };
  52077. /**
  52078. * Specifies if the runtime animation is stopped
  52079. * @returns Boolean specifying if the runtime animation is stopped
  52080. */
  52081. RuntimeAnimation.prototype.isStopped = function () {
  52082. return this._stopped;
  52083. };
  52084. /**
  52085. * Disposes of the runtime animation
  52086. */
  52087. RuntimeAnimation.prototype.dispose = function () {
  52088. var index = this._animation.runtimeAnimations.indexOf(this);
  52089. if (index > -1) {
  52090. this._animation.runtimeAnimations.splice(index, 1);
  52091. }
  52092. };
  52093. /**
  52094. * Interpolates the animation from the current frame
  52095. * @param currentFrame The frame to interpolate the animation to
  52096. * @param repeatCount The number of times that the animation should loop
  52097. * @param loopMode The type of looping mode to use
  52098. * @param offsetValue Animation offset value
  52099. * @param highLimitValue The high limit value
  52100. * @returns The interpolated value
  52101. */
  52102. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52103. this._currentFrame = currentFrame;
  52104. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52105. this._workValue = BABYLON.Matrix.Zero();
  52106. }
  52107. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52108. };
  52109. /**
  52110. * Apply the interpolated value to the target
  52111. * @param currentValue defines the value computed by the animation
  52112. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52113. */
  52114. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52115. if (weight === void 0) { weight = 1.0; }
  52116. if (this._target instanceof Array) {
  52117. var index = 0;
  52118. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52119. var target = _a[_i];
  52120. this._setValue(target, currentValue, weight, index);
  52121. index++;
  52122. }
  52123. }
  52124. else {
  52125. this._setValue(this._target, currentValue, weight);
  52126. }
  52127. };
  52128. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52129. if (targetIndex === void 0) { targetIndex = 0; }
  52130. // Set value
  52131. var path;
  52132. var destination;
  52133. var targetPropertyPath = this._animation.targetPropertyPath;
  52134. if (targetPropertyPath.length > 1) {
  52135. var property = target[targetPropertyPath[0]];
  52136. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52137. property = property[targetPropertyPath[index]];
  52138. }
  52139. path = targetPropertyPath[targetPropertyPath.length - 1];
  52140. destination = property;
  52141. }
  52142. else {
  52143. path = targetPropertyPath[0];
  52144. destination = target;
  52145. }
  52146. this._targetPath = path;
  52147. this._activeTarget = destination;
  52148. this._weight = weight;
  52149. if (this._originalValue[targetIndex] === undefined) {
  52150. var originalValue = void 0;
  52151. if (destination.getRestPose && path === "_matrix") { // For bones
  52152. originalValue = destination.getRestPose();
  52153. }
  52154. else {
  52155. originalValue = destination[path];
  52156. }
  52157. if (originalValue && originalValue.clone) {
  52158. this._originalValue[targetIndex] = originalValue.clone();
  52159. }
  52160. else {
  52161. this._originalValue[targetIndex] = originalValue;
  52162. }
  52163. }
  52164. // Blending
  52165. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52166. if (enableBlending && this._blendingFactor <= 1.0) {
  52167. if (!this._originalBlendValue) {
  52168. var originalValue = destination[path];
  52169. if (originalValue.clone) {
  52170. this._originalBlendValue = originalValue.clone();
  52171. }
  52172. else {
  52173. this._originalBlendValue = originalValue;
  52174. }
  52175. }
  52176. if (this._originalBlendValue.m) { // Matrix
  52177. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52178. if (this._currentValue) {
  52179. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52180. }
  52181. else {
  52182. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52183. }
  52184. }
  52185. else {
  52186. if (this._currentValue) {
  52187. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52188. }
  52189. else {
  52190. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52191. }
  52192. }
  52193. }
  52194. else {
  52195. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52196. }
  52197. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52198. this._blendingFactor += blendingSpeed;
  52199. }
  52200. else {
  52201. this._currentValue = currentValue;
  52202. }
  52203. if (weight !== -1.0) {
  52204. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52205. }
  52206. else {
  52207. destination[path] = this._currentValue;
  52208. }
  52209. if (target.markAsDirty) {
  52210. target.markAsDirty(this._animation.targetProperty);
  52211. }
  52212. };
  52213. /**
  52214. * Gets the loop pmode of the runtime animation
  52215. * @returns Loop Mode
  52216. */
  52217. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52218. if (this._target && this._target.animationPropertiesOverride) {
  52219. return this._target.animationPropertiesOverride.loopMode;
  52220. }
  52221. return this._animation.loopMode;
  52222. };
  52223. /**
  52224. * Move the current animation to a given frame
  52225. * @param frame defines the frame to move to
  52226. */
  52227. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52228. var keys = this._animation.getKeys();
  52229. if (frame < keys[0].frame) {
  52230. frame = keys[0].frame;
  52231. }
  52232. else if (frame > keys[keys.length - 1].frame) {
  52233. frame = keys[keys.length - 1].frame;
  52234. }
  52235. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52236. this.setValue(currentValue, -1);
  52237. };
  52238. /**
  52239. * @hidden Internal use only
  52240. */
  52241. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52242. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52243. this._ratioOffset = this._previousRatio - newRatio;
  52244. };
  52245. /**
  52246. * Execute the current animation
  52247. * @param delay defines the delay to add to the current frame
  52248. * @param from defines the lower bound of the animation range
  52249. * @param to defines the upper bound of the animation range
  52250. * @param loop defines if the current animation must loop
  52251. * @param speedRatio defines the current speed ratio
  52252. * @param weight defines the weight of the animation (default is -1 so no weight)
  52253. * @returns a boolean indicating if the animation is running
  52254. */
  52255. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52256. if (weight === void 0) { weight = -1.0; }
  52257. var targetPropertyPath = this._animation.targetPropertyPath;
  52258. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52259. this._stopped = true;
  52260. return false;
  52261. }
  52262. var returnValue = true;
  52263. var keys = this._animation.getKeys();
  52264. // Adding a start key at frame 0 if missing
  52265. if (keys[0].frame !== 0) {
  52266. var newKey = { frame: 0, value: keys[0].value };
  52267. keys.splice(0, 0, newKey);
  52268. }
  52269. // Adding a duplicate key when there is only one key at frame zero
  52270. else if (keys.length === 1) {
  52271. var newKey = { frame: 0.001, value: keys[0].value };
  52272. keys.push(newKey);
  52273. }
  52274. // Check limits
  52275. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52276. from = keys[0].frame;
  52277. }
  52278. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52279. to = keys[keys.length - 1].frame;
  52280. }
  52281. //to and from cannot be the same key
  52282. if (from === to) {
  52283. if (from > keys[0].frame) {
  52284. from--;
  52285. }
  52286. else if (to < keys[keys.length - 1].frame) {
  52287. to++;
  52288. }
  52289. }
  52290. // Compute ratio
  52291. var range = to - from;
  52292. var offsetValue;
  52293. // ratio represents the frame delta between from and to
  52294. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52295. var highLimitValue = 0;
  52296. this._previousDelay = delay;
  52297. this._previousRatio = ratio;
  52298. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52299. returnValue = false;
  52300. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52301. }
  52302. else {
  52303. // Get max value if required
  52304. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52305. var keyOffset = to.toString() + from.toString();
  52306. if (!this._offsetsCache[keyOffset]) {
  52307. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52308. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52309. switch (this._animation.dataType) {
  52310. // Float
  52311. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52312. this._offsetsCache[keyOffset] = toValue - fromValue;
  52313. break;
  52314. // Quaternion
  52315. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52316. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52317. break;
  52318. // Vector3
  52319. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52320. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52321. // Vector2
  52322. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52323. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52324. // Size
  52325. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52326. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52327. // Color3
  52328. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52329. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52330. default:
  52331. break;
  52332. }
  52333. this._highLimitsCache[keyOffset] = toValue;
  52334. }
  52335. highLimitValue = this._highLimitsCache[keyOffset];
  52336. offsetValue = this._offsetsCache[keyOffset];
  52337. }
  52338. }
  52339. if (offsetValue === undefined) {
  52340. switch (this._animation.dataType) {
  52341. // Float
  52342. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52343. offsetValue = 0;
  52344. break;
  52345. // Quaternion
  52346. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52347. offsetValue = _staticOffsetValueQuaternion;
  52348. break;
  52349. // Vector3
  52350. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52351. offsetValue = _staticOffsetValueVector3;
  52352. break;
  52353. // Vector2
  52354. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52355. offsetValue = _staticOffsetValueVector2;
  52356. break;
  52357. // Size
  52358. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52359. offsetValue = _staticOffsetValueSize;
  52360. break;
  52361. // Color3
  52362. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52363. offsetValue = _staticOffsetValueColor3;
  52364. }
  52365. }
  52366. // Compute value
  52367. var repeatCount = (ratio / range) >> 0;
  52368. var currentFrame = returnValue ? from + ratio % range : to;
  52369. // Need to normalize?
  52370. if (this._host && this._host.syncRoot) {
  52371. var syncRoot = this._host.syncRoot;
  52372. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52373. currentFrame = from + (to - from) * hostNormalizedFrame;
  52374. }
  52375. // Reset events if looping
  52376. var events = this._events;
  52377. if (range > 0 && this.currentFrame > currentFrame ||
  52378. range < 0 && this.currentFrame < currentFrame) {
  52379. // Need to reset animation events
  52380. for (var index = 0; index < events.length; index++) {
  52381. if (!events[index].onlyOnce) {
  52382. // reset event, the animation is looping
  52383. events[index].isDone = false;
  52384. }
  52385. }
  52386. }
  52387. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52388. // Set value
  52389. this.setValue(currentValue, weight);
  52390. // Check events
  52391. for (var index = 0; index < events.length; index++) {
  52392. // Make sure current frame has passed event frame and that event frame is within the current range
  52393. // Also, handle both forward and reverse animations
  52394. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52395. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52396. var event = events[index];
  52397. if (!event.isDone) {
  52398. // If event should be done only once, remove it.
  52399. if (event.onlyOnce) {
  52400. events.splice(index, 1);
  52401. index--;
  52402. }
  52403. event.isDone = true;
  52404. event.action(currentFrame);
  52405. } // Don't do anything if the event has already be done.
  52406. }
  52407. }
  52408. if (!returnValue) {
  52409. this._stopped = true;
  52410. }
  52411. return returnValue;
  52412. };
  52413. return RuntimeAnimation;
  52414. }());
  52415. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52416. })(BABYLON || (BABYLON = {}));
  52417. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52418. var BABYLON;
  52419. (function (BABYLON) {
  52420. /**
  52421. * Class used to store an actual running animation
  52422. */
  52423. var Animatable = /** @class */ (function () {
  52424. /**
  52425. * Creates a new Animatable
  52426. * @param scene defines the hosting scene
  52427. * @param target defines the target object
  52428. * @param fromFrame defines the starting frame number (default is 0)
  52429. * @param toFrame defines the ending frame number (default is 100)
  52430. * @param loopAnimation defines if the animation must loop (default is false)
  52431. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52432. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52433. * @param animations defines a group of animation to add to the new Animatable
  52434. */
  52435. function Animatable(scene,
  52436. /** defines the target object */
  52437. target,
  52438. /** defines the starting frame number (default is 0) */
  52439. fromFrame,
  52440. /** defines the ending frame number (default is 100) */
  52441. toFrame,
  52442. /** defines if the animation must loop (default is false) */
  52443. loopAnimation, speedRatio,
  52444. /** defines a callback to call when animation ends if it is not looping */
  52445. onAnimationEnd, animations) {
  52446. if (fromFrame === void 0) { fromFrame = 0; }
  52447. if (toFrame === void 0) { toFrame = 100; }
  52448. if (loopAnimation === void 0) { loopAnimation = false; }
  52449. if (speedRatio === void 0) { speedRatio = 1.0; }
  52450. this.target = target;
  52451. this.fromFrame = fromFrame;
  52452. this.toFrame = toFrame;
  52453. this.loopAnimation = loopAnimation;
  52454. this.onAnimationEnd = onAnimationEnd;
  52455. this._localDelayOffset = null;
  52456. this._pausedDelay = null;
  52457. this._runtimeAnimations = new Array();
  52458. this._paused = false;
  52459. this._speedRatio = 1;
  52460. this._weight = -1.0;
  52461. /**
  52462. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52463. * This will only apply for non looping animation (default is true)
  52464. */
  52465. this.disposeOnEnd = true;
  52466. /**
  52467. * Gets a boolean indicating if the animation has started
  52468. */
  52469. this.animationStarted = false;
  52470. /**
  52471. * Observer raised when the animation ends
  52472. */
  52473. this.onAnimationEndObservable = new BABYLON.Observable();
  52474. this._scene = scene;
  52475. if (animations) {
  52476. this.appendAnimations(target, animations);
  52477. }
  52478. this._speedRatio = speedRatio;
  52479. scene._activeAnimatables.push(this);
  52480. }
  52481. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52482. /**
  52483. * Gets the root Animatable used to synchronize and normalize animations
  52484. */
  52485. get: function () {
  52486. return this._syncRoot;
  52487. },
  52488. enumerable: true,
  52489. configurable: true
  52490. });
  52491. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52492. /**
  52493. * Gets the current frame of the first RuntimeAnimation
  52494. * Used to synchronize Animatables
  52495. */
  52496. get: function () {
  52497. if (this._runtimeAnimations.length === 0) {
  52498. return 0;
  52499. }
  52500. return this._runtimeAnimations[0].currentFrame;
  52501. },
  52502. enumerable: true,
  52503. configurable: true
  52504. });
  52505. Object.defineProperty(Animatable.prototype, "weight", {
  52506. /**
  52507. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52508. */
  52509. get: function () {
  52510. return this._weight;
  52511. },
  52512. set: function (value) {
  52513. if (value === -1) { // -1 is ok and means no weight
  52514. this._weight = -1;
  52515. return;
  52516. }
  52517. // Else weight must be in [0, 1] range
  52518. this._weight = Math.min(Math.max(value, 0), 1.0);
  52519. },
  52520. enumerable: true,
  52521. configurable: true
  52522. });
  52523. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52524. /**
  52525. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52526. */
  52527. get: function () {
  52528. return this._speedRatio;
  52529. },
  52530. set: function (value) {
  52531. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52532. var animation = this._runtimeAnimations[index];
  52533. animation._prepareForSpeedRatioChange(value);
  52534. }
  52535. this._speedRatio = value;
  52536. },
  52537. enumerable: true,
  52538. configurable: true
  52539. });
  52540. // Methods
  52541. /**
  52542. * Synchronize and normalize current Animatable with a source Animatable
  52543. * This is useful when using animation weights and when animations are not of the same length
  52544. * @param root defines the root Animatable to synchronize with
  52545. * @returns the current Animatable
  52546. */
  52547. Animatable.prototype.syncWith = function (root) {
  52548. this._syncRoot = root;
  52549. if (root) {
  52550. // Make sure this animatable will animate after the root
  52551. var index = this._scene._activeAnimatables.indexOf(this);
  52552. if (index > -1) {
  52553. this._scene._activeAnimatables.splice(index, 1);
  52554. this._scene._activeAnimatables.push(this);
  52555. }
  52556. }
  52557. return this;
  52558. };
  52559. /**
  52560. * Gets the list of runtime animations
  52561. * @returns an array of RuntimeAnimation
  52562. */
  52563. Animatable.prototype.getAnimations = function () {
  52564. return this._runtimeAnimations;
  52565. };
  52566. /**
  52567. * Adds more animations to the current animatable
  52568. * @param target defines the target of the animations
  52569. * @param animations defines the new animations to add
  52570. */
  52571. Animatable.prototype.appendAnimations = function (target, animations) {
  52572. for (var index = 0; index < animations.length; index++) {
  52573. var animation = animations[index];
  52574. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52575. }
  52576. };
  52577. /**
  52578. * Gets the source animation for a specific property
  52579. * @param property defines the propertyu to look for
  52580. * @returns null or the source animation for the given property
  52581. */
  52582. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52583. var runtimeAnimations = this._runtimeAnimations;
  52584. for (var index = 0; index < runtimeAnimations.length; index++) {
  52585. if (runtimeAnimations[index].animation.targetProperty === property) {
  52586. return runtimeAnimations[index].animation;
  52587. }
  52588. }
  52589. return null;
  52590. };
  52591. /**
  52592. * Gets the runtime animation for a specific property
  52593. * @param property defines the propertyu to look for
  52594. * @returns null or the runtime animation for the given property
  52595. */
  52596. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52597. var runtimeAnimations = this._runtimeAnimations;
  52598. for (var index = 0; index < runtimeAnimations.length; index++) {
  52599. if (runtimeAnimations[index].animation.targetProperty === property) {
  52600. return runtimeAnimations[index];
  52601. }
  52602. }
  52603. return null;
  52604. };
  52605. /**
  52606. * Resets the animatable to its original state
  52607. */
  52608. Animatable.prototype.reset = function () {
  52609. var runtimeAnimations = this._runtimeAnimations;
  52610. for (var index = 0; index < runtimeAnimations.length; index++) {
  52611. runtimeAnimations[index].reset(true);
  52612. }
  52613. this._localDelayOffset = null;
  52614. this._pausedDelay = null;
  52615. };
  52616. /**
  52617. * Allows the animatable to blend with current running animations
  52618. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52619. * @param blendingSpeed defines the blending speed to use
  52620. */
  52621. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52622. var runtimeAnimations = this._runtimeAnimations;
  52623. for (var index = 0; index < runtimeAnimations.length; index++) {
  52624. runtimeAnimations[index].animation.enableBlending = true;
  52625. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52626. }
  52627. };
  52628. /**
  52629. * Disable animation blending
  52630. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52631. */
  52632. Animatable.prototype.disableBlending = function () {
  52633. var runtimeAnimations = this._runtimeAnimations;
  52634. for (var index = 0; index < runtimeAnimations.length; index++) {
  52635. runtimeAnimations[index].animation.enableBlending = false;
  52636. }
  52637. };
  52638. /**
  52639. * Jump directly to a given frame
  52640. * @param frame defines the frame to jump to
  52641. */
  52642. Animatable.prototype.goToFrame = function (frame) {
  52643. var runtimeAnimations = this._runtimeAnimations;
  52644. if (runtimeAnimations[0]) {
  52645. var fps = runtimeAnimations[0].animation.framePerSecond;
  52646. var currentFrame = runtimeAnimations[0].currentFrame;
  52647. var adjustTime = frame - currentFrame;
  52648. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52649. if (this._localDelayOffset === null) {
  52650. this._localDelayOffset = 0;
  52651. }
  52652. this._localDelayOffset -= delay;
  52653. }
  52654. for (var index = 0; index < runtimeAnimations.length; index++) {
  52655. runtimeAnimations[index].goToFrame(frame);
  52656. }
  52657. };
  52658. /**
  52659. * Pause the animation
  52660. */
  52661. Animatable.prototype.pause = function () {
  52662. if (this._paused) {
  52663. return;
  52664. }
  52665. this._paused = true;
  52666. };
  52667. /**
  52668. * Restart the animation
  52669. */
  52670. Animatable.prototype.restart = function () {
  52671. this._paused = false;
  52672. };
  52673. Animatable.prototype._raiseOnAnimationEnd = function () {
  52674. if (this.onAnimationEnd) {
  52675. this.onAnimationEnd();
  52676. }
  52677. this.onAnimationEndObservable.notifyObservers(this);
  52678. };
  52679. /**
  52680. * Stop and delete the current animation
  52681. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52682. * @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)
  52683. */
  52684. Animatable.prototype.stop = function (animationName, targetMask) {
  52685. if (animationName || targetMask) {
  52686. var idx = this._scene._activeAnimatables.indexOf(this);
  52687. if (idx > -1) {
  52688. var runtimeAnimations = this._runtimeAnimations;
  52689. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52690. var runtimeAnimation = runtimeAnimations[index];
  52691. if (animationName && runtimeAnimation.animation.name != animationName) {
  52692. continue;
  52693. }
  52694. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52695. continue;
  52696. }
  52697. runtimeAnimation.dispose();
  52698. runtimeAnimations.splice(index, 1);
  52699. }
  52700. if (runtimeAnimations.length == 0) {
  52701. this._scene._activeAnimatables.splice(idx, 1);
  52702. this._raiseOnAnimationEnd();
  52703. }
  52704. }
  52705. }
  52706. else {
  52707. var index = this._scene._activeAnimatables.indexOf(this);
  52708. if (index > -1) {
  52709. this._scene._activeAnimatables.splice(index, 1);
  52710. var runtimeAnimations = this._runtimeAnimations;
  52711. for (var index = 0; index < runtimeAnimations.length; index++) {
  52712. runtimeAnimations[index].dispose();
  52713. }
  52714. this._raiseOnAnimationEnd();
  52715. }
  52716. }
  52717. };
  52718. /**
  52719. * Wait asynchronously for the animation to end
  52720. * @returns a promise which will be fullfilled when the animation ends
  52721. */
  52722. Animatable.prototype.waitAsync = function () {
  52723. var _this = this;
  52724. return new Promise(function (resolve, reject) {
  52725. _this.onAnimationEndObservable.add(function () {
  52726. resolve(_this);
  52727. }, undefined, undefined, _this, true);
  52728. });
  52729. };
  52730. /** @hidden */
  52731. Animatable.prototype._animate = function (delay) {
  52732. if (this._paused) {
  52733. this.animationStarted = false;
  52734. if (this._pausedDelay === null) {
  52735. this._pausedDelay = delay;
  52736. }
  52737. return true;
  52738. }
  52739. if (this._localDelayOffset === null) {
  52740. this._localDelayOffset = delay;
  52741. this._pausedDelay = null;
  52742. }
  52743. else if (this._pausedDelay !== null) {
  52744. this._localDelayOffset += delay - this._pausedDelay;
  52745. this._pausedDelay = null;
  52746. }
  52747. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52748. return true;
  52749. }
  52750. // Animating
  52751. var running = false;
  52752. var runtimeAnimations = this._runtimeAnimations;
  52753. var index;
  52754. for (index = 0; index < runtimeAnimations.length; index++) {
  52755. var animation = runtimeAnimations[index];
  52756. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52757. running = running || isRunning;
  52758. }
  52759. this.animationStarted = running;
  52760. if (!running) {
  52761. if (this.disposeOnEnd) {
  52762. // Remove from active animatables
  52763. index = this._scene._activeAnimatables.indexOf(this);
  52764. this._scene._activeAnimatables.splice(index, 1);
  52765. // Dispose all runtime animations
  52766. for (index = 0; index < runtimeAnimations.length; index++) {
  52767. runtimeAnimations[index].dispose();
  52768. }
  52769. }
  52770. this._raiseOnAnimationEnd();
  52771. if (this.disposeOnEnd) {
  52772. this.onAnimationEnd = null;
  52773. this.onAnimationEndObservable.clear();
  52774. }
  52775. }
  52776. return running;
  52777. };
  52778. return Animatable;
  52779. }());
  52780. BABYLON.Animatable = Animatable;
  52781. })(BABYLON || (BABYLON = {}));
  52782. //# sourceMappingURL=babylon.animatable.js.map
  52783. var BABYLON;
  52784. (function (BABYLON) {
  52785. /**
  52786. * Base class used for every default easing function.
  52787. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52788. */
  52789. var EasingFunction = /** @class */ (function () {
  52790. function EasingFunction() {
  52791. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52792. }
  52793. /**
  52794. * Sets the easing mode of the current function.
  52795. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52796. */
  52797. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52798. var n = Math.min(Math.max(easingMode, 0), 2);
  52799. this._easingMode = n;
  52800. };
  52801. /**
  52802. * Gets the current easing mode.
  52803. * @returns the easing mode
  52804. */
  52805. EasingFunction.prototype.getEasingMode = function () {
  52806. return this._easingMode;
  52807. };
  52808. /**
  52809. * @hidden
  52810. */
  52811. EasingFunction.prototype.easeInCore = function (gradient) {
  52812. throw new Error('You must implement this method');
  52813. };
  52814. /**
  52815. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52816. * of the easing function.
  52817. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52818. * @returns the corresponding value on the curve defined by the easing function
  52819. */
  52820. EasingFunction.prototype.ease = function (gradient) {
  52821. switch (this._easingMode) {
  52822. case EasingFunction.EASINGMODE_EASEIN:
  52823. return this.easeInCore(gradient);
  52824. case EasingFunction.EASINGMODE_EASEOUT:
  52825. return (1 - this.easeInCore(1 - gradient));
  52826. }
  52827. if (gradient >= 0.5) {
  52828. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52829. }
  52830. return (this.easeInCore(gradient * 2) * 0.5);
  52831. };
  52832. /**
  52833. * Interpolation follows the mathematical formula associated with the easing function.
  52834. */
  52835. EasingFunction.EASINGMODE_EASEIN = 0;
  52836. /**
  52837. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52838. */
  52839. EasingFunction.EASINGMODE_EASEOUT = 1;
  52840. /**
  52841. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52842. */
  52843. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52844. return EasingFunction;
  52845. }());
  52846. BABYLON.EasingFunction = EasingFunction;
  52847. /**
  52848. * Easing function with a circle shape (see link below).
  52849. * @see https://easings.net/#easeInCirc
  52850. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52851. */
  52852. var CircleEase = /** @class */ (function (_super) {
  52853. __extends(CircleEase, _super);
  52854. function CircleEase() {
  52855. return _super !== null && _super.apply(this, arguments) || this;
  52856. }
  52857. /** @hidden */
  52858. CircleEase.prototype.easeInCore = function (gradient) {
  52859. gradient = Math.max(0, Math.min(1, gradient));
  52860. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52861. };
  52862. return CircleEase;
  52863. }(EasingFunction));
  52864. BABYLON.CircleEase = CircleEase;
  52865. /**
  52866. * Easing function with a ease back shape (see link below).
  52867. * @see https://easings.net/#easeInBack
  52868. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52869. */
  52870. var BackEase = /** @class */ (function (_super) {
  52871. __extends(BackEase, _super);
  52872. /**
  52873. * Instantiates a back ease easing
  52874. * @see https://easings.net/#easeInBack
  52875. * @param amplitude Defines the amplitude of the function
  52876. */
  52877. function BackEase(
  52878. /** Defines the amplitude of the function */
  52879. amplitude) {
  52880. if (amplitude === void 0) { amplitude = 1; }
  52881. var _this = _super.call(this) || this;
  52882. _this.amplitude = amplitude;
  52883. return _this;
  52884. }
  52885. /** @hidden */
  52886. BackEase.prototype.easeInCore = function (gradient) {
  52887. var num = Math.max(0, this.amplitude);
  52888. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52889. };
  52890. return BackEase;
  52891. }(EasingFunction));
  52892. BABYLON.BackEase = BackEase;
  52893. /**
  52894. * Easing function with a bouncing shape (see link below).
  52895. * @see https://easings.net/#easeInBounce
  52896. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52897. */
  52898. var BounceEase = /** @class */ (function (_super) {
  52899. __extends(BounceEase, _super);
  52900. /**
  52901. * Instantiates a bounce easing
  52902. * @see https://easings.net/#easeInBounce
  52903. * @param bounces Defines the number of bounces
  52904. * @param bounciness Defines the amplitude of the bounce
  52905. */
  52906. function BounceEase(
  52907. /** Defines the number of bounces */
  52908. bounces,
  52909. /** Defines the amplitude of the bounce */
  52910. bounciness) {
  52911. if (bounces === void 0) { bounces = 3; }
  52912. if (bounciness === void 0) { bounciness = 2; }
  52913. var _this = _super.call(this) || this;
  52914. _this.bounces = bounces;
  52915. _this.bounciness = bounciness;
  52916. return _this;
  52917. }
  52918. /** @hidden */
  52919. BounceEase.prototype.easeInCore = function (gradient) {
  52920. var y = Math.max(0.0, this.bounces);
  52921. var bounciness = this.bounciness;
  52922. if (bounciness <= 1.0) {
  52923. bounciness = 1.001;
  52924. }
  52925. var num9 = Math.pow(bounciness, y);
  52926. var num5 = 1.0 - bounciness;
  52927. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52928. var num15 = gradient * num4;
  52929. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52930. var num3 = Math.floor(num65);
  52931. var num13 = num3 + 1.0;
  52932. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52933. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52934. var num7 = (num8 + num12) * 0.5;
  52935. var num6 = gradient - num7;
  52936. var num2 = num7 - num8;
  52937. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52938. };
  52939. return BounceEase;
  52940. }(EasingFunction));
  52941. BABYLON.BounceEase = BounceEase;
  52942. /**
  52943. * Easing function with a power of 3 shape (see link below).
  52944. * @see https://easings.net/#easeInCubic
  52945. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52946. */
  52947. var CubicEase = /** @class */ (function (_super) {
  52948. __extends(CubicEase, _super);
  52949. function CubicEase() {
  52950. return _super !== null && _super.apply(this, arguments) || this;
  52951. }
  52952. /** @hidden */
  52953. CubicEase.prototype.easeInCore = function (gradient) {
  52954. return (gradient * gradient * gradient);
  52955. };
  52956. return CubicEase;
  52957. }(EasingFunction));
  52958. BABYLON.CubicEase = CubicEase;
  52959. /**
  52960. * Easing function with an elastic shape (see link below).
  52961. * @see https://easings.net/#easeInElastic
  52962. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52963. */
  52964. var ElasticEase = /** @class */ (function (_super) {
  52965. __extends(ElasticEase, _super);
  52966. /**
  52967. * Instantiates an elastic easing function
  52968. * @see https://easings.net/#easeInElastic
  52969. * @param oscillations Defines the number of oscillations
  52970. * @param springiness Defines the amplitude of the oscillations
  52971. */
  52972. function ElasticEase(
  52973. /** Defines the number of oscillations*/
  52974. oscillations,
  52975. /** Defines the amplitude of the oscillations*/
  52976. springiness) {
  52977. if (oscillations === void 0) { oscillations = 3; }
  52978. if (springiness === void 0) { springiness = 3; }
  52979. var _this = _super.call(this) || this;
  52980. _this.oscillations = oscillations;
  52981. _this.springiness = springiness;
  52982. return _this;
  52983. }
  52984. /** @hidden */
  52985. ElasticEase.prototype.easeInCore = function (gradient) {
  52986. var num2;
  52987. var num3 = Math.max(0.0, this.oscillations);
  52988. var num = Math.max(0.0, this.springiness);
  52989. if (num == 0) {
  52990. num2 = gradient;
  52991. }
  52992. else {
  52993. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52994. }
  52995. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52996. };
  52997. return ElasticEase;
  52998. }(EasingFunction));
  52999. BABYLON.ElasticEase = ElasticEase;
  53000. /**
  53001. * Easing function with an exponential shape (see link below).
  53002. * @see https://easings.net/#easeInExpo
  53003. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53004. */
  53005. var ExponentialEase = /** @class */ (function (_super) {
  53006. __extends(ExponentialEase, _super);
  53007. /**
  53008. * Instantiates an exponential easing function
  53009. * @see https://easings.net/#easeInExpo
  53010. * @param exponent Defines the exponent of the function
  53011. */
  53012. function ExponentialEase(
  53013. /** Defines the exponent of the function */
  53014. exponent) {
  53015. if (exponent === void 0) { exponent = 2; }
  53016. var _this = _super.call(this) || this;
  53017. _this.exponent = exponent;
  53018. return _this;
  53019. }
  53020. /** @hidden */
  53021. ExponentialEase.prototype.easeInCore = function (gradient) {
  53022. if (this.exponent <= 0) {
  53023. return gradient;
  53024. }
  53025. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  53026. };
  53027. return ExponentialEase;
  53028. }(EasingFunction));
  53029. BABYLON.ExponentialEase = ExponentialEase;
  53030. /**
  53031. * Easing function with a power shape (see link below).
  53032. * @see https://easings.net/#easeInQuad
  53033. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53034. */
  53035. var PowerEase = /** @class */ (function (_super) {
  53036. __extends(PowerEase, _super);
  53037. /**
  53038. * Instantiates an power base easing function
  53039. * @see https://easings.net/#easeInQuad
  53040. * @param power Defines the power of the function
  53041. */
  53042. function PowerEase(
  53043. /** Defines the power of the function */
  53044. power) {
  53045. if (power === void 0) { power = 2; }
  53046. var _this = _super.call(this) || this;
  53047. _this.power = power;
  53048. return _this;
  53049. }
  53050. /** @hidden */
  53051. PowerEase.prototype.easeInCore = function (gradient) {
  53052. var y = Math.max(0.0, this.power);
  53053. return Math.pow(gradient, y);
  53054. };
  53055. return PowerEase;
  53056. }(EasingFunction));
  53057. BABYLON.PowerEase = PowerEase;
  53058. /**
  53059. * Easing function with a power of 2 shape (see link below).
  53060. * @see https://easings.net/#easeInQuad
  53061. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53062. */
  53063. var QuadraticEase = /** @class */ (function (_super) {
  53064. __extends(QuadraticEase, _super);
  53065. function QuadraticEase() {
  53066. return _super !== null && _super.apply(this, arguments) || this;
  53067. }
  53068. /** @hidden */
  53069. QuadraticEase.prototype.easeInCore = function (gradient) {
  53070. return (gradient * gradient);
  53071. };
  53072. return QuadraticEase;
  53073. }(EasingFunction));
  53074. BABYLON.QuadraticEase = QuadraticEase;
  53075. /**
  53076. * Easing function with a power of 4 shape (see link below).
  53077. * @see https://easings.net/#easeInQuart
  53078. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53079. */
  53080. var QuarticEase = /** @class */ (function (_super) {
  53081. __extends(QuarticEase, _super);
  53082. function QuarticEase() {
  53083. return _super !== null && _super.apply(this, arguments) || this;
  53084. }
  53085. /** @hidden */
  53086. QuarticEase.prototype.easeInCore = function (gradient) {
  53087. return (gradient * gradient * gradient * gradient);
  53088. };
  53089. return QuarticEase;
  53090. }(EasingFunction));
  53091. BABYLON.QuarticEase = QuarticEase;
  53092. /**
  53093. * Easing function with a power of 5 shape (see link below).
  53094. * @see https://easings.net/#easeInQuint
  53095. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53096. */
  53097. var QuinticEase = /** @class */ (function (_super) {
  53098. __extends(QuinticEase, _super);
  53099. function QuinticEase() {
  53100. return _super !== null && _super.apply(this, arguments) || this;
  53101. }
  53102. /** @hidden */
  53103. QuinticEase.prototype.easeInCore = function (gradient) {
  53104. return (gradient * gradient * gradient * gradient * gradient);
  53105. };
  53106. return QuinticEase;
  53107. }(EasingFunction));
  53108. BABYLON.QuinticEase = QuinticEase;
  53109. /**
  53110. * Easing function with a sin shape (see link below).
  53111. * @see https://easings.net/#easeInSine
  53112. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53113. */
  53114. var SineEase = /** @class */ (function (_super) {
  53115. __extends(SineEase, _super);
  53116. function SineEase() {
  53117. return _super !== null && _super.apply(this, arguments) || this;
  53118. }
  53119. /** @hidden */
  53120. SineEase.prototype.easeInCore = function (gradient) {
  53121. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53122. };
  53123. return SineEase;
  53124. }(EasingFunction));
  53125. BABYLON.SineEase = SineEase;
  53126. /**
  53127. * Easing function with a bezier shape (see link below).
  53128. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53129. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53130. */
  53131. var BezierCurveEase = /** @class */ (function (_super) {
  53132. __extends(BezierCurveEase, _super);
  53133. /**
  53134. * Instantiates a bezier function
  53135. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  53136. * @param x1 Defines the x component of the start tangent in the bezier curve
  53137. * @param y1 Defines the y component of the start tangent in the bezier curve
  53138. * @param x2 Defines the x component of the end tangent in the bezier curve
  53139. * @param y2 Defines the y component of the end tangent in the bezier curve
  53140. */
  53141. function BezierCurveEase(
  53142. /** Defines the x component of the start tangent in the bezier curve */
  53143. x1,
  53144. /** Defines the y component of the start tangent in the bezier curve */
  53145. y1,
  53146. /** Defines the x component of the end tangent in the bezier curve */
  53147. x2,
  53148. /** Defines the y component of the end tangent in the bezier curve */
  53149. y2) {
  53150. if (x1 === void 0) { x1 = 0; }
  53151. if (y1 === void 0) { y1 = 0; }
  53152. if (x2 === void 0) { x2 = 1; }
  53153. if (y2 === void 0) { y2 = 1; }
  53154. var _this = _super.call(this) || this;
  53155. _this.x1 = x1;
  53156. _this.y1 = y1;
  53157. _this.x2 = x2;
  53158. _this.y2 = y2;
  53159. return _this;
  53160. }
  53161. /** @hidden */
  53162. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53163. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53164. };
  53165. return BezierCurveEase;
  53166. }(EasingFunction));
  53167. BABYLON.BezierCurveEase = BezierCurveEase;
  53168. })(BABYLON || (BABYLON = {}));
  53169. //# sourceMappingURL=babylon.easing.js.map
  53170. var BABYLON;
  53171. (function (BABYLON) {
  53172. /**
  53173. * A Condition applied to an Action
  53174. */
  53175. var Condition = /** @class */ (function () {
  53176. /**
  53177. * Creates a new Condition
  53178. * @param actionManager the manager of the action the condition is applied to
  53179. */
  53180. function Condition(actionManager) {
  53181. this._actionManager = actionManager;
  53182. }
  53183. /**
  53184. * Check if the current condition is valid
  53185. * @returns a boolean
  53186. */
  53187. Condition.prototype.isValid = function () {
  53188. return true;
  53189. };
  53190. /**
  53191. * Internal only
  53192. * @hidden
  53193. */
  53194. Condition.prototype._getProperty = function (propertyPath) {
  53195. return this._actionManager._getProperty(propertyPath);
  53196. };
  53197. /**
  53198. * Internal only
  53199. * @hidden
  53200. */
  53201. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53202. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53203. };
  53204. /**
  53205. * Serialize placeholder for child classes
  53206. * @returns the serialized object
  53207. */
  53208. Condition.prototype.serialize = function () {
  53209. };
  53210. /**
  53211. * Internal only
  53212. * @hidden
  53213. */
  53214. Condition.prototype._serialize = function (serializedCondition) {
  53215. return {
  53216. type: 2,
  53217. children: [],
  53218. name: serializedCondition.name,
  53219. properties: serializedCondition.properties
  53220. };
  53221. };
  53222. return Condition;
  53223. }());
  53224. BABYLON.Condition = Condition;
  53225. /**
  53226. * Defines specific conditional operators as extensions of Condition
  53227. */
  53228. var ValueCondition = /** @class */ (function (_super) {
  53229. __extends(ValueCondition, _super);
  53230. /**
  53231. * Creates a new ValueCondition
  53232. * @param actionManager manager for the action the condition applies to
  53233. * @param target for the action
  53234. * @param propertyPath path to specify the property of the target the conditional operator uses
  53235. * @param value the value compared by the conditional operator against the current value of the property
  53236. * @param operator the conditional operator, default ValueCondition.IsEqual
  53237. */
  53238. function ValueCondition(actionManager, target,
  53239. /** path to specify the property of the target the conditional operator uses */
  53240. propertyPath,
  53241. /** the value compared by the conditional operator against the current value of the property */
  53242. value,
  53243. /** the conditional operator, default ValueCondition.IsEqual */
  53244. operator) {
  53245. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53246. var _this = _super.call(this, actionManager) || this;
  53247. _this.propertyPath = propertyPath;
  53248. _this.value = value;
  53249. _this.operator = operator;
  53250. _this._target = target;
  53251. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53252. _this._property = _this._getProperty(_this.propertyPath);
  53253. return _this;
  53254. }
  53255. Object.defineProperty(ValueCondition, "IsEqual", {
  53256. /**
  53257. * returns the number for IsEqual
  53258. */
  53259. get: function () {
  53260. return ValueCondition._IsEqual;
  53261. },
  53262. enumerable: true,
  53263. configurable: true
  53264. });
  53265. Object.defineProperty(ValueCondition, "IsDifferent", {
  53266. /**
  53267. * Returns the number for IsDifferent
  53268. */
  53269. get: function () {
  53270. return ValueCondition._IsDifferent;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. Object.defineProperty(ValueCondition, "IsGreater", {
  53276. /**
  53277. * Returns the number for IsGreater
  53278. */
  53279. get: function () {
  53280. return ValueCondition._IsGreater;
  53281. },
  53282. enumerable: true,
  53283. configurable: true
  53284. });
  53285. Object.defineProperty(ValueCondition, "IsLesser", {
  53286. /**
  53287. * Returns the number for IsLesser
  53288. */
  53289. get: function () {
  53290. return ValueCondition._IsLesser;
  53291. },
  53292. enumerable: true,
  53293. configurable: true
  53294. });
  53295. /**
  53296. * Compares the given value with the property value for the specified conditional operator
  53297. * @returns the result of the comparison
  53298. */
  53299. ValueCondition.prototype.isValid = function () {
  53300. switch (this.operator) {
  53301. case ValueCondition.IsGreater:
  53302. return this._effectiveTarget[this._property] > this.value;
  53303. case ValueCondition.IsLesser:
  53304. return this._effectiveTarget[this._property] < this.value;
  53305. case ValueCondition.IsEqual:
  53306. case ValueCondition.IsDifferent:
  53307. var check;
  53308. if (this.value.equals) {
  53309. check = this.value.equals(this._effectiveTarget[this._property]);
  53310. }
  53311. else {
  53312. check = this.value === this._effectiveTarget[this._property];
  53313. }
  53314. return this.operator === ValueCondition.IsEqual ? check : !check;
  53315. }
  53316. return false;
  53317. };
  53318. /**
  53319. * Serialize the ValueCondition into a JSON compatible object
  53320. * @returns serialization object
  53321. */
  53322. ValueCondition.prototype.serialize = function () {
  53323. return this._serialize({
  53324. name: "ValueCondition",
  53325. properties: [
  53326. BABYLON.Action._GetTargetProperty(this._target),
  53327. { name: "propertyPath", value: this.propertyPath },
  53328. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53329. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53330. ]
  53331. });
  53332. };
  53333. /**
  53334. * Gets the name of the conditional operator for the ValueCondition
  53335. * @param operator the conditional operator
  53336. * @returns the name
  53337. */
  53338. ValueCondition.GetOperatorName = function (operator) {
  53339. switch (operator) {
  53340. case ValueCondition._IsEqual: return "IsEqual";
  53341. case ValueCondition._IsDifferent: return "IsDifferent";
  53342. case ValueCondition._IsGreater: return "IsGreater";
  53343. case ValueCondition._IsLesser: return "IsLesser";
  53344. default: return "";
  53345. }
  53346. };
  53347. /**
  53348. * Internal only
  53349. * @hidden
  53350. */
  53351. ValueCondition._IsEqual = 0;
  53352. /**
  53353. * Internal only
  53354. * @hidden
  53355. */
  53356. ValueCondition._IsDifferent = 1;
  53357. /**
  53358. * Internal only
  53359. * @hidden
  53360. */
  53361. ValueCondition._IsGreater = 2;
  53362. /**
  53363. * Internal only
  53364. * @hidden
  53365. */
  53366. ValueCondition._IsLesser = 3;
  53367. return ValueCondition;
  53368. }(Condition));
  53369. BABYLON.ValueCondition = ValueCondition;
  53370. /**
  53371. * Defines a predicate condition as an extension of Condition
  53372. */
  53373. var PredicateCondition = /** @class */ (function (_super) {
  53374. __extends(PredicateCondition, _super);
  53375. /**
  53376. * Creates a new PredicateCondition
  53377. * @param actionManager manager for the action the condition applies to
  53378. * @param predicate defines the predicate function used to validate the condition
  53379. */
  53380. function PredicateCondition(actionManager,
  53381. /** defines the predicate function used to validate the condition */
  53382. predicate) {
  53383. var _this = _super.call(this, actionManager) || this;
  53384. _this.predicate = predicate;
  53385. return _this;
  53386. }
  53387. /**
  53388. * @returns the validity of the predicate condition
  53389. */
  53390. PredicateCondition.prototype.isValid = function () {
  53391. return this.predicate();
  53392. };
  53393. return PredicateCondition;
  53394. }(Condition));
  53395. BABYLON.PredicateCondition = PredicateCondition;
  53396. /**
  53397. * Defines a state condition as an extension of Condition
  53398. */
  53399. var StateCondition = /** @class */ (function (_super) {
  53400. __extends(StateCondition, _super);
  53401. /**
  53402. * Creates a new StateCondition
  53403. * @param actionManager manager for the action the condition applies to
  53404. * @param target of the condition
  53405. * @param value to compare with target state
  53406. */
  53407. function StateCondition(actionManager, target, value) {
  53408. var _this = _super.call(this, actionManager) || this;
  53409. _this.value = value;
  53410. _this._target = target;
  53411. return _this;
  53412. }
  53413. /**
  53414. * @returns the validity of the state
  53415. */
  53416. StateCondition.prototype.isValid = function () {
  53417. return this._target.state === this.value;
  53418. };
  53419. /**
  53420. * Serialize the StateCondition into a JSON compatible object
  53421. * @returns serialization object
  53422. */
  53423. StateCondition.prototype.serialize = function () {
  53424. return this._serialize({
  53425. name: "StateCondition",
  53426. properties: [
  53427. BABYLON.Action._GetTargetProperty(this._target),
  53428. { name: "value", value: this.value }
  53429. ]
  53430. });
  53431. };
  53432. return StateCondition;
  53433. }(Condition));
  53434. BABYLON.StateCondition = StateCondition;
  53435. })(BABYLON || (BABYLON = {}));
  53436. //# sourceMappingURL=babylon.condition.js.map
  53437. var BABYLON;
  53438. (function (BABYLON) {
  53439. /**
  53440. * The action to be carried out following a trigger
  53441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53442. */
  53443. var Action = /** @class */ (function () {
  53444. /**
  53445. * Creates a new Action
  53446. * @param triggerOptions the trigger, with or without parameters, for the action
  53447. * @param condition an optional determinant of action
  53448. */
  53449. function Action(
  53450. /** the trigger, with or without parameters, for the action */
  53451. triggerOptions, condition) {
  53452. this.triggerOptions = triggerOptions;
  53453. /**
  53454. * An event triggered prior to action being executed.
  53455. */
  53456. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53457. if (triggerOptions.parameter) {
  53458. this.trigger = triggerOptions.trigger;
  53459. this._triggerParameter = triggerOptions.parameter;
  53460. }
  53461. else if (triggerOptions.trigger) {
  53462. this.trigger = triggerOptions.trigger;
  53463. }
  53464. else {
  53465. this.trigger = triggerOptions;
  53466. }
  53467. this._nextActiveAction = this;
  53468. this._condition = condition;
  53469. }
  53470. /**
  53471. * Internal only
  53472. * @hidden
  53473. */
  53474. Action.prototype._prepare = function () {
  53475. };
  53476. /**
  53477. * Gets the trigger parameters
  53478. * @returns the trigger parameters
  53479. */
  53480. Action.prototype.getTriggerParameter = function () {
  53481. return this._triggerParameter;
  53482. };
  53483. /**
  53484. * Internal only - executes current action event
  53485. * @hidden
  53486. */
  53487. Action.prototype._executeCurrent = function (evt) {
  53488. if (this._nextActiveAction._condition) {
  53489. var condition = this._nextActiveAction._condition;
  53490. var currentRenderId = this._actionManager.getScene().getRenderId();
  53491. // We cache the current evaluation for the current frame
  53492. if (condition._evaluationId === currentRenderId) {
  53493. if (!condition._currentResult) {
  53494. return;
  53495. }
  53496. }
  53497. else {
  53498. condition._evaluationId = currentRenderId;
  53499. if (!condition.isValid()) {
  53500. condition._currentResult = false;
  53501. return;
  53502. }
  53503. condition._currentResult = true;
  53504. }
  53505. }
  53506. this.onBeforeExecuteObservable.notifyObservers(this);
  53507. this._nextActiveAction.execute(evt);
  53508. this.skipToNextActiveAction();
  53509. };
  53510. /**
  53511. * Execute placeholder for child classes
  53512. * @param evt optional action event
  53513. */
  53514. Action.prototype.execute = function (evt) {
  53515. };
  53516. /**
  53517. * Skips to next active action
  53518. */
  53519. Action.prototype.skipToNextActiveAction = function () {
  53520. if (this._nextActiveAction._child) {
  53521. if (!this._nextActiveAction._child._actionManager) {
  53522. this._nextActiveAction._child._actionManager = this._actionManager;
  53523. }
  53524. this._nextActiveAction = this._nextActiveAction._child;
  53525. }
  53526. else {
  53527. this._nextActiveAction = this;
  53528. }
  53529. };
  53530. /**
  53531. * Adds action to chain of actions, may be a DoNothingAction
  53532. * @param action defines the next action to execute
  53533. * @returns The action passed in
  53534. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53535. */
  53536. Action.prototype.then = function (action) {
  53537. this._child = action;
  53538. action._actionManager = this._actionManager;
  53539. action._prepare();
  53540. return action;
  53541. };
  53542. /**
  53543. * Internal only
  53544. * @hidden
  53545. */
  53546. Action.prototype._getProperty = function (propertyPath) {
  53547. return this._actionManager._getProperty(propertyPath);
  53548. };
  53549. /**
  53550. * Internal only
  53551. * @hidden
  53552. */
  53553. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53554. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53555. };
  53556. /**
  53557. * Serialize placeholder for child classes
  53558. * @param parent of child
  53559. * @returns the serialized object
  53560. */
  53561. Action.prototype.serialize = function (parent) {
  53562. };
  53563. /**
  53564. * Internal only called by serialize
  53565. * @hidden
  53566. */
  53567. Action.prototype._serialize = function (serializedAction, parent) {
  53568. var serializationObject = {
  53569. type: 1,
  53570. children: [],
  53571. name: serializedAction.name,
  53572. properties: serializedAction.properties || []
  53573. };
  53574. // Serialize child
  53575. if (this._child) {
  53576. this._child.serialize(serializationObject);
  53577. }
  53578. // Check if "this" has a condition
  53579. if (this._condition) {
  53580. var serializedCondition = this._condition.serialize();
  53581. serializedCondition.children.push(serializationObject);
  53582. if (parent) {
  53583. parent.children.push(serializedCondition);
  53584. }
  53585. return serializedCondition;
  53586. }
  53587. if (parent) {
  53588. parent.children.push(serializationObject);
  53589. }
  53590. return serializationObject;
  53591. };
  53592. /**
  53593. * Internal only
  53594. * @hidden
  53595. */
  53596. Action._SerializeValueAsString = function (value) {
  53597. if (typeof value === "number") {
  53598. return value.toString();
  53599. }
  53600. if (typeof value === "boolean") {
  53601. return value ? "true" : "false";
  53602. }
  53603. if (value instanceof BABYLON.Vector2) {
  53604. return value.x + ", " + value.y;
  53605. }
  53606. if (value instanceof BABYLON.Vector3) {
  53607. return value.x + ", " + value.y + ", " + value.z;
  53608. }
  53609. if (value instanceof BABYLON.Color3) {
  53610. return value.r + ", " + value.g + ", " + value.b;
  53611. }
  53612. if (value instanceof BABYLON.Color4) {
  53613. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53614. }
  53615. return value; // string
  53616. };
  53617. /**
  53618. * Internal only
  53619. * @hidden
  53620. */
  53621. Action._GetTargetProperty = function (target) {
  53622. return {
  53623. name: "target",
  53624. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53625. : target instanceof BABYLON.Light ? "LightProperties"
  53626. : target instanceof BABYLON.Camera ? "CameraProperties"
  53627. : "SceneProperties",
  53628. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53629. };
  53630. };
  53631. return Action;
  53632. }());
  53633. BABYLON.Action = Action;
  53634. })(BABYLON || (BABYLON = {}));
  53635. //# sourceMappingURL=babylon.action.js.map
  53636. var BABYLON;
  53637. (function (BABYLON) {
  53638. /**
  53639. * ActionEvent is the event being sent when an action is triggered.
  53640. */
  53641. var ActionEvent = /** @class */ (function () {
  53642. /**
  53643. * Creates a new ActionEvent
  53644. * @param source The mesh or sprite that triggered the action
  53645. * @param pointerX The X mouse cursor position at the time of the event
  53646. * @param pointerY The Y mouse cursor position at the time of the event
  53647. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53648. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53649. * @param additionalData additional data for the event
  53650. */
  53651. function ActionEvent(
  53652. /** The mesh or sprite that triggered the action */
  53653. source,
  53654. /** The X mouse cursor position at the time of the event */
  53655. pointerX,
  53656. /** The Y mouse cursor position at the time of the event */
  53657. pointerY,
  53658. /** The mesh that is currently pointed at (can be null) */
  53659. meshUnderPointer,
  53660. /** the original (browser) event that triggered the ActionEvent */
  53661. sourceEvent,
  53662. /** additional data for the event */
  53663. additionalData) {
  53664. this.source = source;
  53665. this.pointerX = pointerX;
  53666. this.pointerY = pointerY;
  53667. this.meshUnderPointer = meshUnderPointer;
  53668. this.sourceEvent = sourceEvent;
  53669. this.additionalData = additionalData;
  53670. }
  53671. /**
  53672. * Helper function to auto-create an ActionEvent from a source mesh.
  53673. * @param source The source mesh that triggered the event
  53674. * @param evt The original (browser) event
  53675. * @param additionalData additional data for the event
  53676. * @returns the new ActionEvent
  53677. */
  53678. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53679. var scene = source.getScene();
  53680. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53681. };
  53682. /**
  53683. * Helper function to auto-create an ActionEvent from a source sprite
  53684. * @param source The source sprite that triggered the event
  53685. * @param scene Scene associated with the sprite
  53686. * @param evt The original (browser) event
  53687. * @param additionalData additional data for the event
  53688. * @returns the new ActionEvent
  53689. */
  53690. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53691. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53692. };
  53693. /**
  53694. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53695. * @param scene the scene where the event occurred
  53696. * @param evt The original (browser) event
  53697. * @returns the new ActionEvent
  53698. */
  53699. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53700. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53701. };
  53702. /**
  53703. * Helper function to auto-create an ActionEvent from a primitive
  53704. * @param prim defines the target primitive
  53705. * @param pointerPos defines the pointer position
  53706. * @param evt The original (browser) event
  53707. * @param additionalData additional data for the event
  53708. * @returns the new ActionEvent
  53709. */
  53710. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53711. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53712. };
  53713. return ActionEvent;
  53714. }());
  53715. BABYLON.ActionEvent = ActionEvent;
  53716. /**
  53717. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53718. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53719. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53720. */
  53721. var ActionManager = /** @class */ (function () {
  53722. /**
  53723. * Creates a new action manager
  53724. * @param scene defines the hosting scene
  53725. */
  53726. function ActionManager(scene) {
  53727. // Members
  53728. /** Gets the list of actions */
  53729. this.actions = new Array();
  53730. /** Gets the cursor to use when hovering items */
  53731. this.hoverCursor = '';
  53732. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53733. scene.actionManagers.push(this);
  53734. }
  53735. // Methods
  53736. /**
  53737. * Releases all associated resources
  53738. */
  53739. ActionManager.prototype.dispose = function () {
  53740. var index = this._scene.actionManagers.indexOf(this);
  53741. for (var i = 0; i < this.actions.length; i++) {
  53742. var action = this.actions[i];
  53743. ActionManager.Triggers[action.trigger]--;
  53744. if (ActionManager.Triggers[action.trigger] === 0) {
  53745. delete ActionManager.Triggers[action.trigger];
  53746. }
  53747. }
  53748. if (index > -1) {
  53749. this._scene.actionManagers.splice(index, 1);
  53750. }
  53751. };
  53752. /**
  53753. * Gets hosting scene
  53754. * @returns the hosting scene
  53755. */
  53756. ActionManager.prototype.getScene = function () {
  53757. return this._scene;
  53758. };
  53759. /**
  53760. * Does this action manager handles actions of any of the given triggers
  53761. * @param triggers defines the triggers to be tested
  53762. * @return a boolean indicating whether one (or more) of the triggers is handled
  53763. */
  53764. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53765. for (var index = 0; index < this.actions.length; index++) {
  53766. var action = this.actions[index];
  53767. if (triggers.indexOf(action.trigger) > -1) {
  53768. return true;
  53769. }
  53770. }
  53771. return false;
  53772. };
  53773. /**
  53774. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53775. * speed.
  53776. * @param triggerA defines the trigger to be tested
  53777. * @param triggerB defines the trigger to be tested
  53778. * @return a boolean indicating whether one (or more) of the triggers is handled
  53779. */
  53780. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53781. for (var index = 0; index < this.actions.length; index++) {
  53782. var action = this.actions[index];
  53783. if (triggerA == action.trigger || triggerB == action.trigger) {
  53784. return true;
  53785. }
  53786. }
  53787. return false;
  53788. };
  53789. /**
  53790. * Does this action manager handles actions of a given trigger
  53791. * @param trigger defines the trigger to be tested
  53792. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53793. * @return whether the trigger is handled
  53794. */
  53795. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53796. for (var index = 0; index < this.actions.length; index++) {
  53797. var action = this.actions[index];
  53798. if (action.trigger === trigger) {
  53799. if (parameterPredicate) {
  53800. if (parameterPredicate(action.getTriggerParameter())) {
  53801. return true;
  53802. }
  53803. }
  53804. else {
  53805. return true;
  53806. }
  53807. }
  53808. }
  53809. return false;
  53810. };
  53811. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53812. /**
  53813. * Does this action manager has pointer triggers
  53814. */
  53815. get: function () {
  53816. for (var index = 0; index < this.actions.length; index++) {
  53817. var action = this.actions[index];
  53818. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53819. return true;
  53820. }
  53821. }
  53822. return false;
  53823. },
  53824. enumerable: true,
  53825. configurable: true
  53826. });
  53827. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53828. /**
  53829. * Does this action manager has pick triggers
  53830. */
  53831. get: function () {
  53832. for (var index = 0; index < this.actions.length; index++) {
  53833. var action = this.actions[index];
  53834. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53835. return true;
  53836. }
  53837. }
  53838. return false;
  53839. },
  53840. enumerable: true,
  53841. configurable: true
  53842. });
  53843. Object.defineProperty(ActionManager, "HasTriggers", {
  53844. /**
  53845. * Does exist one action manager with at least one trigger
  53846. **/
  53847. get: function () {
  53848. for (var t in ActionManager.Triggers) {
  53849. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53850. return true;
  53851. }
  53852. }
  53853. return false;
  53854. },
  53855. enumerable: true,
  53856. configurable: true
  53857. });
  53858. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53859. /**
  53860. * Does exist one action manager with at least one pick trigger
  53861. **/
  53862. get: function () {
  53863. for (var t in ActionManager.Triggers) {
  53864. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53865. var t_int = parseInt(t);
  53866. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53867. return true;
  53868. }
  53869. }
  53870. }
  53871. return false;
  53872. },
  53873. enumerable: true,
  53874. configurable: true
  53875. });
  53876. /**
  53877. * Does exist one action manager that handles actions of a given trigger
  53878. * @param trigger defines the trigger to be tested
  53879. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53880. **/
  53881. ActionManager.HasSpecificTrigger = function (trigger) {
  53882. for (var t in ActionManager.Triggers) {
  53883. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53884. var t_int = parseInt(t);
  53885. if (t_int === trigger) {
  53886. return true;
  53887. }
  53888. }
  53889. }
  53890. return false;
  53891. };
  53892. /**
  53893. * Registers an action to this action manager
  53894. * @param action defines the action to be registered
  53895. * @return the action amended (prepared) after registration
  53896. */
  53897. ActionManager.prototype.registerAction = function (action) {
  53898. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53899. if (this.getScene().actionManager !== this) {
  53900. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53901. return null;
  53902. }
  53903. }
  53904. this.actions.push(action);
  53905. if (ActionManager.Triggers[action.trigger]) {
  53906. ActionManager.Triggers[action.trigger]++;
  53907. }
  53908. else {
  53909. ActionManager.Triggers[action.trigger] = 1;
  53910. }
  53911. action._actionManager = this;
  53912. action._prepare();
  53913. return action;
  53914. };
  53915. /**
  53916. * Unregisters an action to this action manager
  53917. * @param action defines the action to be unregistered
  53918. * @return a boolean indicating whether the action has been unregistered
  53919. */
  53920. ActionManager.prototype.unregisterAction = function (action) {
  53921. var index = this.actions.indexOf(action);
  53922. if (index !== -1) {
  53923. this.actions.splice(index, 1);
  53924. ActionManager.Triggers[action.trigger] -= 1;
  53925. if (ActionManager.Triggers[action.trigger] === 0) {
  53926. delete ActionManager.Triggers[action.trigger];
  53927. }
  53928. delete action._actionManager;
  53929. return true;
  53930. }
  53931. return false;
  53932. };
  53933. /**
  53934. * Process a specific trigger
  53935. * @param trigger defines the trigger to process
  53936. * @param evt defines the event details to be processed
  53937. */
  53938. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53939. for (var index = 0; index < this.actions.length; index++) {
  53940. var action = this.actions[index];
  53941. if (action.trigger === trigger) {
  53942. if (evt) {
  53943. if (trigger === ActionManager.OnKeyUpTrigger
  53944. || trigger === ActionManager.OnKeyDownTrigger) {
  53945. var parameter = action.getTriggerParameter();
  53946. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53947. if (!parameter.toLowerCase) {
  53948. continue;
  53949. }
  53950. var lowerCase = parameter.toLowerCase();
  53951. if (lowerCase !== evt.sourceEvent.key) {
  53952. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53953. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53954. if (actualkey !== lowerCase) {
  53955. continue;
  53956. }
  53957. }
  53958. }
  53959. }
  53960. }
  53961. action._executeCurrent(evt);
  53962. }
  53963. }
  53964. };
  53965. /** @hidden */
  53966. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53967. var properties = propertyPath.split(".");
  53968. for (var index = 0; index < properties.length - 1; index++) {
  53969. target = target[properties[index]];
  53970. }
  53971. return target;
  53972. };
  53973. /** @hidden */
  53974. ActionManager.prototype._getProperty = function (propertyPath) {
  53975. var properties = propertyPath.split(".");
  53976. return properties[properties.length - 1];
  53977. };
  53978. /**
  53979. * Serialize this manager to a JSON object
  53980. * @param name defines the property name to store this manager
  53981. * @returns a JSON representation of this manager
  53982. */
  53983. ActionManager.prototype.serialize = function (name) {
  53984. var root = {
  53985. children: new Array(),
  53986. name: name,
  53987. type: 3,
  53988. properties: new Array() // Empty for root but required
  53989. };
  53990. for (var i = 0; i < this.actions.length; i++) {
  53991. var triggerObject = {
  53992. type: 0,
  53993. children: new Array(),
  53994. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53995. properties: new Array()
  53996. };
  53997. var triggerOptions = this.actions[i].triggerOptions;
  53998. if (triggerOptions && typeof triggerOptions !== "number") {
  53999. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54000. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54001. }
  54002. else {
  54003. var parameter = {};
  54004. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54005. if (triggerOptions.parameter.mesh) {
  54006. parameter._meshId = triggerOptions.parameter.mesh.id;
  54007. }
  54008. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54009. }
  54010. }
  54011. // Serialize child action, recursively
  54012. this.actions[i].serialize(triggerObject);
  54013. // Add serialized trigger
  54014. root.children.push(triggerObject);
  54015. }
  54016. return root;
  54017. };
  54018. /**
  54019. * Creates a new ActionManager from a JSON data
  54020. * @param parsedActions defines the JSON data to read from
  54021. * @param object defines the hosting mesh
  54022. * @param scene defines the hosting scene
  54023. */
  54024. ActionManager.Parse = function (parsedActions, object, scene) {
  54025. var actionManager = new ActionManager(scene);
  54026. if (object === null)
  54027. scene.actionManager = actionManager;
  54028. else
  54029. object.actionManager = actionManager;
  54030. // instanciate a new object
  54031. var instanciate = function (name, params) {
  54032. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54033. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54034. newInstance.constructor.apply(newInstance, params);
  54035. return newInstance;
  54036. };
  54037. var parseParameter = function (name, value, target, propertyPath) {
  54038. if (propertyPath === null) {
  54039. // String, boolean or float
  54040. var floatValue = parseFloat(value);
  54041. if (value === "true" || value === "false")
  54042. return value === "true";
  54043. else
  54044. return isNaN(floatValue) ? value : floatValue;
  54045. }
  54046. var effectiveTarget = propertyPath.split(".");
  54047. var values = value.split(",");
  54048. // Get effective Target
  54049. for (var i = 0; i < effectiveTarget.length; i++) {
  54050. target = target[effectiveTarget[i]];
  54051. }
  54052. // Return appropriate value with its type
  54053. if (typeof (target) === "boolean")
  54054. return values[0] === "true";
  54055. if (typeof (target) === "string")
  54056. return values[0];
  54057. // Parameters with multiple values such as Vector3 etc.
  54058. var split = new Array();
  54059. for (var i = 0; i < values.length; i++)
  54060. split.push(parseFloat(values[i]));
  54061. if (target instanceof BABYLON.Vector3)
  54062. return BABYLON.Vector3.FromArray(split);
  54063. if (target instanceof BABYLON.Vector4)
  54064. return BABYLON.Vector4.FromArray(split);
  54065. if (target instanceof BABYLON.Color3)
  54066. return BABYLON.Color3.FromArray(split);
  54067. if (target instanceof BABYLON.Color4)
  54068. return BABYLON.Color4.FromArray(split);
  54069. return parseFloat(values[0]);
  54070. };
  54071. // traverse graph per trigger
  54072. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54073. if (combineArray === void 0) { combineArray = null; }
  54074. if (parsedAction.detached)
  54075. return;
  54076. var parameters = new Array();
  54077. var target = null;
  54078. var propertyPath = null;
  54079. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54080. // Parameters
  54081. if (parsedAction.type === 2)
  54082. parameters.push(actionManager);
  54083. else
  54084. parameters.push(trigger);
  54085. if (combine) {
  54086. var actions = new Array();
  54087. for (var j = 0; j < parsedAction.combine.length; j++) {
  54088. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54089. }
  54090. parameters.push(actions);
  54091. }
  54092. else {
  54093. for (var i = 0; i < parsedAction.properties.length; i++) {
  54094. var value = parsedAction.properties[i].value;
  54095. var name = parsedAction.properties[i].name;
  54096. var targetType = parsedAction.properties[i].targetType;
  54097. if (name === "target")
  54098. if (targetType !== null && targetType === "SceneProperties")
  54099. value = target = scene;
  54100. else
  54101. value = target = scene.getNodeByName(value);
  54102. else if (name === "parent")
  54103. value = scene.getNodeByName(value);
  54104. else if (name === "sound") {
  54105. // Can not externalize to component, so only checks for the presence off the API.
  54106. if (scene.getSoundByName) {
  54107. value = scene.getSoundByName(value);
  54108. }
  54109. }
  54110. else if (name !== "propertyPath") {
  54111. if (parsedAction.type === 2 && name === "operator")
  54112. value = BABYLON.ValueCondition[value];
  54113. else
  54114. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54115. }
  54116. else {
  54117. propertyPath = value;
  54118. }
  54119. parameters.push(value);
  54120. }
  54121. }
  54122. if (combineArray === null) {
  54123. parameters.push(condition);
  54124. }
  54125. else {
  54126. parameters.push(null);
  54127. }
  54128. // If interpolate value action
  54129. if (parsedAction.name === "InterpolateValueAction") {
  54130. var param = parameters[parameters.length - 2];
  54131. parameters[parameters.length - 1] = param;
  54132. parameters[parameters.length - 2] = condition;
  54133. }
  54134. // Action or condition(s) and not CombineAction
  54135. var newAction = instanciate(parsedAction.name, parameters);
  54136. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54137. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54138. if (action)
  54139. action.then(nothing);
  54140. else
  54141. actionManager.registerAction(nothing);
  54142. action = nothing;
  54143. }
  54144. if (combineArray === null) {
  54145. if (newAction instanceof BABYLON.Condition) {
  54146. condition = newAction;
  54147. newAction = action;
  54148. }
  54149. else {
  54150. condition = null;
  54151. if (action)
  54152. action.then(newAction);
  54153. else
  54154. actionManager.registerAction(newAction);
  54155. }
  54156. }
  54157. else {
  54158. combineArray.push(newAction);
  54159. }
  54160. for (var i = 0; i < parsedAction.children.length; i++)
  54161. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54162. };
  54163. // triggers
  54164. for (var i = 0; i < parsedActions.children.length; i++) {
  54165. var triggerParams;
  54166. var trigger = parsedActions.children[i];
  54167. if (trigger.properties.length > 0) {
  54168. var param = trigger.properties[0].value;
  54169. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54170. if (value._meshId) {
  54171. value.mesh = scene.getMeshByID(value._meshId);
  54172. }
  54173. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54174. }
  54175. else
  54176. triggerParams = ActionManager[trigger.name];
  54177. for (var j = 0; j < trigger.children.length; j++) {
  54178. if (!trigger.detached)
  54179. traverse(trigger.children[j], triggerParams, null, null);
  54180. }
  54181. }
  54182. };
  54183. /**
  54184. * Get a trigger name by index
  54185. * @param trigger defines the trigger index
  54186. * @returns a trigger name
  54187. */
  54188. ActionManager.GetTriggerName = function (trigger) {
  54189. switch (trigger) {
  54190. case 0: return "NothingTrigger";
  54191. case 1: return "OnPickTrigger";
  54192. case 2: return "OnLeftPickTrigger";
  54193. case 3: return "OnRightPickTrigger";
  54194. case 4: return "OnCenterPickTrigger";
  54195. case 5: return "OnPickDownTrigger";
  54196. case 6: return "OnPickUpTrigger";
  54197. case 7: return "OnLongPressTrigger";
  54198. case 8: return "OnPointerOverTrigger";
  54199. case 9: return "OnPointerOutTrigger";
  54200. case 10: return "OnEveryFrameTrigger";
  54201. case 11: return "OnIntersectionEnterTrigger";
  54202. case 12: return "OnIntersectionExitTrigger";
  54203. case 13: return "OnKeyDownTrigger";
  54204. case 14: return "OnKeyUpTrigger";
  54205. case 15: return "OnPickOutTrigger";
  54206. default: return "";
  54207. }
  54208. };
  54209. /**
  54210. * Nothing
  54211. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54212. */
  54213. ActionManager.NothingTrigger = 0;
  54214. /**
  54215. * On pick
  54216. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54217. */
  54218. ActionManager.OnPickTrigger = 1;
  54219. /**
  54220. * On left pick
  54221. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54222. */
  54223. ActionManager.OnLeftPickTrigger = 2;
  54224. /**
  54225. * On right pick
  54226. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54227. */
  54228. ActionManager.OnRightPickTrigger = 3;
  54229. /**
  54230. * On center pick
  54231. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54232. */
  54233. ActionManager.OnCenterPickTrigger = 4;
  54234. /**
  54235. * On pick down
  54236. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54237. */
  54238. ActionManager.OnPickDownTrigger = 5;
  54239. /**
  54240. * On double pick
  54241. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54242. */
  54243. ActionManager.OnDoublePickTrigger = 6;
  54244. /**
  54245. * On pick up
  54246. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54247. */
  54248. ActionManager.OnPickUpTrigger = 7;
  54249. /**
  54250. * On pick out.
  54251. * This trigger will only be raised if you also declared a OnPickDown
  54252. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54253. */
  54254. ActionManager.OnPickOutTrigger = 16;
  54255. /**
  54256. * On long press
  54257. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54258. */
  54259. ActionManager.OnLongPressTrigger = 8;
  54260. /**
  54261. * On pointer over
  54262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54263. */
  54264. ActionManager.OnPointerOverTrigger = 9;
  54265. /**
  54266. * On pointer out
  54267. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54268. */
  54269. ActionManager.OnPointerOutTrigger = 10;
  54270. /**
  54271. * On every frame
  54272. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54273. */
  54274. ActionManager.OnEveryFrameTrigger = 11;
  54275. /**
  54276. * On intersection enter
  54277. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54278. */
  54279. ActionManager.OnIntersectionEnterTrigger = 12;
  54280. /**
  54281. * On intersection exit
  54282. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54283. */
  54284. ActionManager.OnIntersectionExitTrigger = 13;
  54285. /**
  54286. * On key down
  54287. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54288. */
  54289. ActionManager.OnKeyDownTrigger = 14;
  54290. /**
  54291. * On key up
  54292. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54293. */
  54294. ActionManager.OnKeyUpTrigger = 15;
  54295. /** Gets the list of active triggers */
  54296. ActionManager.Triggers = {};
  54297. return ActionManager;
  54298. }());
  54299. BABYLON.ActionManager = ActionManager;
  54300. })(BABYLON || (BABYLON = {}));
  54301. //# sourceMappingURL=babylon.actionManager.js.map
  54302. var BABYLON;
  54303. (function (BABYLON) {
  54304. /**
  54305. * This defines an action responsible to change the value of a property
  54306. * by interpolating between its current value and the newly set one once triggered.
  54307. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54308. */
  54309. var InterpolateValueAction = /** @class */ (function (_super) {
  54310. __extends(InterpolateValueAction, _super);
  54311. /**
  54312. * Instantiate the action
  54313. * @param triggerOptions defines the trigger options
  54314. * @param target defines the object containing the value to interpolate
  54315. * @param propertyPath defines the path to the property in the target object
  54316. * @param value defines the target value at the end of the interpolation
  54317. * @param duration deines the time it will take for the property to interpolate to the value.
  54318. * @param condition defines the trigger related conditions
  54319. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54320. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54321. */
  54322. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54323. if (duration === void 0) { duration = 1000; }
  54324. var _this = _super.call(this, triggerOptions, condition) || this;
  54325. /**
  54326. * Defines the time it will take for the property to interpolate to the value.
  54327. */
  54328. _this.duration = 1000;
  54329. /**
  54330. * Observable triggered once the interpolation animation has been done.
  54331. */
  54332. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54333. _this.propertyPath = propertyPath;
  54334. _this.value = value;
  54335. _this.duration = duration;
  54336. _this.stopOtherAnimations = stopOtherAnimations;
  54337. _this.onInterpolationDone = onInterpolationDone;
  54338. _this._target = _this._effectiveTarget = target;
  54339. return _this;
  54340. }
  54341. /** @hidden */
  54342. InterpolateValueAction.prototype._prepare = function () {
  54343. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54344. this._property = this._getProperty(this.propertyPath);
  54345. };
  54346. /**
  54347. * Execute the action starts the value interpolation.
  54348. */
  54349. InterpolateValueAction.prototype.execute = function () {
  54350. var _this = this;
  54351. var scene = this._actionManager.getScene();
  54352. var keys = [
  54353. {
  54354. frame: 0,
  54355. value: this._effectiveTarget[this._property]
  54356. }, {
  54357. frame: 100,
  54358. value: this.value
  54359. }
  54360. ];
  54361. var dataType;
  54362. if (typeof this.value === "number") {
  54363. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54364. }
  54365. else if (this.value instanceof BABYLON.Color3) {
  54366. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54367. }
  54368. else if (this.value instanceof BABYLON.Vector3) {
  54369. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54370. }
  54371. else if (this.value instanceof BABYLON.Matrix) {
  54372. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54373. }
  54374. else if (this.value instanceof BABYLON.Quaternion) {
  54375. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54376. }
  54377. else {
  54378. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54379. return;
  54380. }
  54381. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54382. animation.setKeys(keys);
  54383. if (this.stopOtherAnimations) {
  54384. scene.stopAnimation(this._effectiveTarget);
  54385. }
  54386. var wrapper = function () {
  54387. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54388. if (_this.onInterpolationDone) {
  54389. _this.onInterpolationDone();
  54390. }
  54391. };
  54392. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54393. };
  54394. /**
  54395. * Serializes the actions and its related information.
  54396. * @param parent defines the object to serialize in
  54397. * @returns the serialized object
  54398. */
  54399. InterpolateValueAction.prototype.serialize = function (parent) {
  54400. return _super.prototype._serialize.call(this, {
  54401. name: "InterpolateValueAction",
  54402. properties: [
  54403. BABYLON.Action._GetTargetProperty(this._target),
  54404. { name: "propertyPath", value: this.propertyPath },
  54405. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54406. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54407. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54408. ]
  54409. }, parent);
  54410. };
  54411. return InterpolateValueAction;
  54412. }(BABYLON.Action));
  54413. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54414. })(BABYLON || (BABYLON = {}));
  54415. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54416. var BABYLON;
  54417. (function (BABYLON) {
  54418. /**
  54419. * This defines an action responsible to toggle a boolean once triggered.
  54420. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54421. */
  54422. var SwitchBooleanAction = /** @class */ (function (_super) {
  54423. __extends(SwitchBooleanAction, _super);
  54424. /**
  54425. * Instantiate the action
  54426. * @param triggerOptions defines the trigger options
  54427. * @param target defines the object containing the boolean
  54428. * @param propertyPath defines the path to the boolean property in the target object
  54429. * @param condition defines the trigger related conditions
  54430. */
  54431. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54432. var _this = _super.call(this, triggerOptions, condition) || this;
  54433. _this.propertyPath = propertyPath;
  54434. _this._target = _this._effectiveTarget = target;
  54435. return _this;
  54436. }
  54437. /** @hidden */
  54438. SwitchBooleanAction.prototype._prepare = function () {
  54439. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54440. this._property = this._getProperty(this.propertyPath);
  54441. };
  54442. /**
  54443. * Execute the action toggle the boolean value.
  54444. */
  54445. SwitchBooleanAction.prototype.execute = function () {
  54446. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54447. };
  54448. /**
  54449. * Serializes the actions and its related information.
  54450. * @param parent defines the object to serialize in
  54451. * @returns the serialized object
  54452. */
  54453. SwitchBooleanAction.prototype.serialize = function (parent) {
  54454. return _super.prototype._serialize.call(this, {
  54455. name: "SwitchBooleanAction",
  54456. properties: [
  54457. BABYLON.Action._GetTargetProperty(this._target),
  54458. { name: "propertyPath", value: this.propertyPath }
  54459. ]
  54460. }, parent);
  54461. };
  54462. return SwitchBooleanAction;
  54463. }(BABYLON.Action));
  54464. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54465. /**
  54466. * This defines an action responsible to set a the state field of the target
  54467. * to a desired value once triggered.
  54468. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54469. */
  54470. var SetStateAction = /** @class */ (function (_super) {
  54471. __extends(SetStateAction, _super);
  54472. /**
  54473. * Instantiate the action
  54474. * @param triggerOptions defines the trigger options
  54475. * @param target defines the object containing the state property
  54476. * @param value defines the value to store in the state field
  54477. * @param condition defines the trigger related conditions
  54478. */
  54479. function SetStateAction(triggerOptions, target, value, condition) {
  54480. var _this = _super.call(this, triggerOptions, condition) || this;
  54481. _this.value = value;
  54482. _this._target = target;
  54483. return _this;
  54484. }
  54485. /**
  54486. * Execute the action and store the value on the target state property.
  54487. */
  54488. SetStateAction.prototype.execute = function () {
  54489. this._target.state = this.value;
  54490. };
  54491. /**
  54492. * Serializes the actions and its related information.
  54493. * @param parent defines the object to serialize in
  54494. * @returns the serialized object
  54495. */
  54496. SetStateAction.prototype.serialize = function (parent) {
  54497. return _super.prototype._serialize.call(this, {
  54498. name: "SetStateAction",
  54499. properties: [
  54500. BABYLON.Action._GetTargetProperty(this._target),
  54501. { name: "value", value: this.value }
  54502. ]
  54503. }, parent);
  54504. };
  54505. return SetStateAction;
  54506. }(BABYLON.Action));
  54507. BABYLON.SetStateAction = SetStateAction;
  54508. /**
  54509. * This defines an action responsible to set a property of the target
  54510. * to a desired value once triggered.
  54511. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54512. */
  54513. var SetValueAction = /** @class */ (function (_super) {
  54514. __extends(SetValueAction, _super);
  54515. /**
  54516. * Instantiate the action
  54517. * @param triggerOptions defines the trigger options
  54518. * @param target defines the object containing the property
  54519. * @param propertyPath defines the path of the property to set in the target
  54520. * @param value defines the value to set in the property
  54521. * @param condition defines the trigger related conditions
  54522. */
  54523. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54524. var _this = _super.call(this, triggerOptions, condition) || this;
  54525. _this.propertyPath = propertyPath;
  54526. _this.value = value;
  54527. _this._target = _this._effectiveTarget = target;
  54528. return _this;
  54529. }
  54530. /** @hidden */
  54531. SetValueAction.prototype._prepare = function () {
  54532. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54533. this._property = this._getProperty(this.propertyPath);
  54534. };
  54535. /**
  54536. * Execute the action and set the targetted property to the desired value.
  54537. */
  54538. SetValueAction.prototype.execute = function () {
  54539. this._effectiveTarget[this._property] = this.value;
  54540. if (this._target.markAsDirty) {
  54541. this._target.markAsDirty(this._property);
  54542. }
  54543. };
  54544. /**
  54545. * Serializes the actions and its related information.
  54546. * @param parent defines the object to serialize in
  54547. * @returns the serialized object
  54548. */
  54549. SetValueAction.prototype.serialize = function (parent) {
  54550. return _super.prototype._serialize.call(this, {
  54551. name: "SetValueAction",
  54552. properties: [
  54553. BABYLON.Action._GetTargetProperty(this._target),
  54554. { name: "propertyPath", value: this.propertyPath },
  54555. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54556. ]
  54557. }, parent);
  54558. };
  54559. return SetValueAction;
  54560. }(BABYLON.Action));
  54561. BABYLON.SetValueAction = SetValueAction;
  54562. /**
  54563. * This defines an action responsible to increment the target value
  54564. * to a desired value once triggered.
  54565. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54566. */
  54567. var IncrementValueAction = /** @class */ (function (_super) {
  54568. __extends(IncrementValueAction, _super);
  54569. /**
  54570. * Instantiate the action
  54571. * @param triggerOptions defines the trigger options
  54572. * @param target defines the object containing the property
  54573. * @param propertyPath defines the path of the property to increment in the target
  54574. * @param value defines the value value we should increment the property by
  54575. * @param condition defines the trigger related conditions
  54576. */
  54577. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54578. var _this = _super.call(this, triggerOptions, condition) || this;
  54579. _this.propertyPath = propertyPath;
  54580. _this.value = value;
  54581. _this._target = _this._effectiveTarget = target;
  54582. return _this;
  54583. }
  54584. /** @hidden */
  54585. IncrementValueAction.prototype._prepare = function () {
  54586. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54587. this._property = this._getProperty(this.propertyPath);
  54588. if (typeof this._effectiveTarget[this._property] !== "number") {
  54589. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54590. }
  54591. };
  54592. /**
  54593. * Execute the action and increment the target of the value amount.
  54594. */
  54595. IncrementValueAction.prototype.execute = function () {
  54596. this._effectiveTarget[this._property] += this.value;
  54597. if (this._target.markAsDirty) {
  54598. this._target.markAsDirty(this._property);
  54599. }
  54600. };
  54601. /**
  54602. * Serializes the actions and its related information.
  54603. * @param parent defines the object to serialize in
  54604. * @returns the serialized object
  54605. */
  54606. IncrementValueAction.prototype.serialize = function (parent) {
  54607. return _super.prototype._serialize.call(this, {
  54608. name: "IncrementValueAction",
  54609. properties: [
  54610. BABYLON.Action._GetTargetProperty(this._target),
  54611. { name: "propertyPath", value: this.propertyPath },
  54612. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54613. ]
  54614. }, parent);
  54615. };
  54616. return IncrementValueAction;
  54617. }(BABYLON.Action));
  54618. BABYLON.IncrementValueAction = IncrementValueAction;
  54619. /**
  54620. * This defines an action responsible to start an animation once triggered.
  54621. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54622. */
  54623. var PlayAnimationAction = /** @class */ (function (_super) {
  54624. __extends(PlayAnimationAction, _super);
  54625. /**
  54626. * Instantiate the action
  54627. * @param triggerOptions defines the trigger options
  54628. * @param target defines the target animation or animation name
  54629. * @param from defines from where the animation should start (animation frame)
  54630. * @param end defines where the animation should stop (animation frame)
  54631. * @param loop defines if the animation should loop or stop after the first play
  54632. * @param condition defines the trigger related conditions
  54633. */
  54634. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54635. var _this = _super.call(this, triggerOptions, condition) || this;
  54636. _this.from = from;
  54637. _this.to = to;
  54638. _this.loop = loop;
  54639. _this._target = target;
  54640. return _this;
  54641. }
  54642. /** @hidden */
  54643. PlayAnimationAction.prototype._prepare = function () {
  54644. };
  54645. /**
  54646. * Execute the action and play the animation.
  54647. */
  54648. PlayAnimationAction.prototype.execute = function () {
  54649. var scene = this._actionManager.getScene();
  54650. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54651. };
  54652. /**
  54653. * Serializes the actions and its related information.
  54654. * @param parent defines the object to serialize in
  54655. * @returns the serialized object
  54656. */
  54657. PlayAnimationAction.prototype.serialize = function (parent) {
  54658. return _super.prototype._serialize.call(this, {
  54659. name: "PlayAnimationAction",
  54660. properties: [
  54661. BABYLON.Action._GetTargetProperty(this._target),
  54662. { name: "from", value: String(this.from) },
  54663. { name: "to", value: String(this.to) },
  54664. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54665. ]
  54666. }, parent);
  54667. };
  54668. return PlayAnimationAction;
  54669. }(BABYLON.Action));
  54670. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54671. /**
  54672. * This defines an action responsible to stop an animation once triggered.
  54673. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54674. */
  54675. var StopAnimationAction = /** @class */ (function (_super) {
  54676. __extends(StopAnimationAction, _super);
  54677. /**
  54678. * Instantiate the action
  54679. * @param triggerOptions defines the trigger options
  54680. * @param target defines the target animation or animation name
  54681. * @param condition defines the trigger related conditions
  54682. */
  54683. function StopAnimationAction(triggerOptions, target, condition) {
  54684. var _this = _super.call(this, triggerOptions, condition) || this;
  54685. _this._target = target;
  54686. return _this;
  54687. }
  54688. /** @hidden */
  54689. StopAnimationAction.prototype._prepare = function () {
  54690. };
  54691. /**
  54692. * Execute the action and stop the animation.
  54693. */
  54694. StopAnimationAction.prototype.execute = function () {
  54695. var scene = this._actionManager.getScene();
  54696. scene.stopAnimation(this._target);
  54697. };
  54698. /**
  54699. * Serializes the actions and its related information.
  54700. * @param parent defines the object to serialize in
  54701. * @returns the serialized object
  54702. */
  54703. StopAnimationAction.prototype.serialize = function (parent) {
  54704. return _super.prototype._serialize.call(this, {
  54705. name: "StopAnimationAction",
  54706. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54707. }, parent);
  54708. };
  54709. return StopAnimationAction;
  54710. }(BABYLON.Action));
  54711. BABYLON.StopAnimationAction = StopAnimationAction;
  54712. /**
  54713. * This defines an action responsible that does nothing once triggered.
  54714. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54715. */
  54716. var DoNothingAction = /** @class */ (function (_super) {
  54717. __extends(DoNothingAction, _super);
  54718. /**
  54719. * Instantiate the action
  54720. * @param triggerOptions defines the trigger options
  54721. * @param condition defines the trigger related conditions
  54722. */
  54723. function DoNothingAction(triggerOptions, condition) {
  54724. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54725. return _super.call(this, triggerOptions, condition) || this;
  54726. }
  54727. /**
  54728. * Execute the action and do nothing.
  54729. */
  54730. DoNothingAction.prototype.execute = function () {
  54731. };
  54732. /**
  54733. * Serializes the actions and its related information.
  54734. * @param parent defines the object to serialize in
  54735. * @returns the serialized object
  54736. */
  54737. DoNothingAction.prototype.serialize = function (parent) {
  54738. return _super.prototype._serialize.call(this, {
  54739. name: "DoNothingAction",
  54740. properties: []
  54741. }, parent);
  54742. };
  54743. return DoNothingAction;
  54744. }(BABYLON.Action));
  54745. BABYLON.DoNothingAction = DoNothingAction;
  54746. /**
  54747. * This defines an action responsible to trigger several actions once triggered.
  54748. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54749. */
  54750. var CombineAction = /** @class */ (function (_super) {
  54751. __extends(CombineAction, _super);
  54752. /**
  54753. * Instantiate the action
  54754. * @param triggerOptions defines the trigger options
  54755. * @param children defines the list of aggregated animations to run
  54756. * @param condition defines the trigger related conditions
  54757. */
  54758. function CombineAction(triggerOptions, children, condition) {
  54759. var _this = _super.call(this, triggerOptions, condition) || this;
  54760. _this.children = children;
  54761. return _this;
  54762. }
  54763. /** @hidden */
  54764. CombineAction.prototype._prepare = function () {
  54765. for (var index = 0; index < this.children.length; index++) {
  54766. this.children[index]._actionManager = this._actionManager;
  54767. this.children[index]._prepare();
  54768. }
  54769. };
  54770. /**
  54771. * Execute the action and executes all the aggregated actions.
  54772. */
  54773. CombineAction.prototype.execute = function (evt) {
  54774. for (var index = 0; index < this.children.length; index++) {
  54775. this.children[index].execute(evt);
  54776. }
  54777. };
  54778. /**
  54779. * Serializes the actions and its related information.
  54780. * @param parent defines the object to serialize in
  54781. * @returns the serialized object
  54782. */
  54783. CombineAction.prototype.serialize = function (parent) {
  54784. var serializationObject = _super.prototype._serialize.call(this, {
  54785. name: "CombineAction",
  54786. properties: [],
  54787. combine: []
  54788. }, parent);
  54789. for (var i = 0; i < this.children.length; i++) {
  54790. serializationObject.combine.push(this.children[i].serialize(null));
  54791. }
  54792. return serializationObject;
  54793. };
  54794. return CombineAction;
  54795. }(BABYLON.Action));
  54796. BABYLON.CombineAction = CombineAction;
  54797. /**
  54798. * This defines an action responsible to run code (external event) once triggered.
  54799. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54800. */
  54801. var ExecuteCodeAction = /** @class */ (function (_super) {
  54802. __extends(ExecuteCodeAction, _super);
  54803. /**
  54804. * Instantiate the action
  54805. * @param triggerOptions defines the trigger options
  54806. * @param func defines the callback function to run
  54807. * @param condition defines the trigger related conditions
  54808. */
  54809. function ExecuteCodeAction(triggerOptions, func, condition) {
  54810. var _this = _super.call(this, triggerOptions, condition) || this;
  54811. _this.func = func;
  54812. return _this;
  54813. }
  54814. /**
  54815. * Execute the action and run the attached code.
  54816. */
  54817. ExecuteCodeAction.prototype.execute = function (evt) {
  54818. this.func(evt);
  54819. };
  54820. return ExecuteCodeAction;
  54821. }(BABYLON.Action));
  54822. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54823. /**
  54824. * This defines an action responsible to set the parent property of the target once triggered.
  54825. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54826. */
  54827. var SetParentAction = /** @class */ (function (_super) {
  54828. __extends(SetParentAction, _super);
  54829. /**
  54830. * Instantiate the action
  54831. * @param triggerOptions defines the trigger options
  54832. * @param target defines the target containing the parent property
  54833. * @param parent defines from where the animation should start (animation frame)
  54834. * @param condition defines the trigger related conditions
  54835. */
  54836. function SetParentAction(triggerOptions, target, parent, condition) {
  54837. var _this = _super.call(this, triggerOptions, condition) || this;
  54838. _this._target = target;
  54839. _this._parent = parent;
  54840. return _this;
  54841. }
  54842. /** @hidden */
  54843. SetParentAction.prototype._prepare = function () {
  54844. };
  54845. /**
  54846. * Execute the action and set the parent property.
  54847. */
  54848. SetParentAction.prototype.execute = function () {
  54849. if (this._target.parent === this._parent) {
  54850. return;
  54851. }
  54852. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54853. invertParentWorldMatrix.invert();
  54854. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54855. this._target.parent = this._parent;
  54856. };
  54857. /**
  54858. * Serializes the actions and its related information.
  54859. * @param parent defines the object to serialize in
  54860. * @returns the serialized object
  54861. */
  54862. SetParentAction.prototype.serialize = function (parent) {
  54863. return _super.prototype._serialize.call(this, {
  54864. name: "SetParentAction",
  54865. properties: [
  54866. BABYLON.Action._GetTargetProperty(this._target),
  54867. BABYLON.Action._GetTargetProperty(this._parent),
  54868. ]
  54869. }, parent);
  54870. };
  54871. return SetParentAction;
  54872. }(BABYLON.Action));
  54873. BABYLON.SetParentAction = SetParentAction;
  54874. })(BABYLON || (BABYLON = {}));
  54875. //# sourceMappingURL=babylon.directActions.js.map
  54876. var BABYLON;
  54877. (function (BABYLON) {
  54878. var SpriteManager = /** @class */ (function () {
  54879. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54880. if (epsilon === void 0) { epsilon = 0.01; }
  54881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54882. this.name = name;
  54883. this.sprites = new Array();
  54884. this.renderingGroupId = 0;
  54885. this.layerMask = 0x0FFFFFFF;
  54886. this.fogEnabled = true;
  54887. this.isPickable = false;
  54888. /**
  54889. * An event triggered when the manager is disposed.
  54890. */
  54891. this.onDisposeObservable = new BABYLON.Observable();
  54892. this._vertexBuffers = {};
  54893. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54894. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54895. }
  54896. this._capacity = capacity;
  54897. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54898. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54899. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54900. if (cellSize.width && cellSize.height) {
  54901. this.cellWidth = cellSize.width;
  54902. this.cellHeight = cellSize.height;
  54903. }
  54904. else if (cellSize !== undefined) {
  54905. this.cellWidth = cellSize;
  54906. this.cellHeight = cellSize;
  54907. }
  54908. else {
  54909. return;
  54910. }
  54911. this._epsilon = epsilon;
  54912. this._scene = scene;
  54913. this._scene.spriteManagers.push(this);
  54914. var indices = [];
  54915. var index = 0;
  54916. for (var count = 0; count < capacity; count++) {
  54917. indices.push(index);
  54918. indices.push(index + 1);
  54919. indices.push(index + 2);
  54920. indices.push(index);
  54921. indices.push(index + 2);
  54922. indices.push(index + 3);
  54923. index += 4;
  54924. }
  54925. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54926. // VBO
  54927. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54928. this._vertexData = new Float32Array(capacity * 16 * 4);
  54929. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54930. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54931. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54932. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54933. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54934. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54935. this._vertexBuffers["options"] = options;
  54936. this._vertexBuffers["cellInfo"] = cellInfo;
  54937. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54938. // Effects
  54939. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54940. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54941. }
  54942. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54943. set: function (callback) {
  54944. if (this._onDisposeObserver) {
  54945. this.onDisposeObservable.remove(this._onDisposeObserver);
  54946. }
  54947. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54948. },
  54949. enumerable: true,
  54950. configurable: true
  54951. });
  54952. Object.defineProperty(SpriteManager.prototype, "texture", {
  54953. get: function () {
  54954. return this._spriteTexture;
  54955. },
  54956. set: function (value) {
  54957. this._spriteTexture = value;
  54958. },
  54959. enumerable: true,
  54960. configurable: true
  54961. });
  54962. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54963. var arrayOffset = index * 16;
  54964. if (offsetX === 0)
  54965. offsetX = this._epsilon;
  54966. else if (offsetX === 1)
  54967. offsetX = 1 - this._epsilon;
  54968. if (offsetY === 0)
  54969. offsetY = this._epsilon;
  54970. else if (offsetY === 1)
  54971. offsetY = 1 - this._epsilon;
  54972. this._vertexData[arrayOffset] = sprite.position.x;
  54973. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54974. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54975. this._vertexData[arrayOffset + 3] = sprite.angle;
  54976. this._vertexData[arrayOffset + 4] = sprite.width;
  54977. this._vertexData[arrayOffset + 5] = sprite.height;
  54978. this._vertexData[arrayOffset + 6] = offsetX;
  54979. this._vertexData[arrayOffset + 7] = offsetY;
  54980. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54981. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54982. var offset = (sprite.cellIndex / rowSize) >> 0;
  54983. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54984. this._vertexData[arrayOffset + 11] = offset;
  54985. // Color
  54986. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54987. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54988. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54989. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54990. };
  54991. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54992. var count = Math.min(this._capacity, this.sprites.length);
  54993. var min = BABYLON.Vector3.Zero();
  54994. var max = BABYLON.Vector3.Zero();
  54995. var distance = Number.MAX_VALUE;
  54996. var currentSprite = null;
  54997. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54998. var cameraView = camera.getViewMatrix();
  54999. for (var index = 0; index < count; index++) {
  55000. var sprite = this.sprites[index];
  55001. if (!sprite) {
  55002. continue;
  55003. }
  55004. if (predicate) {
  55005. if (!predicate(sprite)) {
  55006. continue;
  55007. }
  55008. }
  55009. else if (!sprite.isPickable) {
  55010. continue;
  55011. }
  55012. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55013. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55014. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55015. if (ray.intersectsBoxMinMax(min, max)) {
  55016. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  55017. if (distance > currentDistance) {
  55018. distance = currentDistance;
  55019. currentSprite = sprite;
  55020. if (fastCheck) {
  55021. break;
  55022. }
  55023. }
  55024. }
  55025. }
  55026. if (currentSprite) {
  55027. var result = new BABYLON.PickingInfo();
  55028. result.hit = true;
  55029. result.pickedSprite = currentSprite;
  55030. result.distance = distance;
  55031. return result;
  55032. }
  55033. return null;
  55034. };
  55035. SpriteManager.prototype.render = function () {
  55036. // Check
  55037. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  55038. return;
  55039. var engine = this._scene.getEngine();
  55040. var baseSize = this._spriteTexture.getBaseSize();
  55041. // Sprites
  55042. var deltaTime = engine.getDeltaTime();
  55043. var max = Math.min(this._capacity, this.sprites.length);
  55044. var rowSize = baseSize.width / this.cellWidth;
  55045. var offset = 0;
  55046. for (var index = 0; index < max; index++) {
  55047. var sprite = this.sprites[index];
  55048. if (!sprite || !sprite.isVisible) {
  55049. continue;
  55050. }
  55051. sprite._animate(deltaTime);
  55052. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  55053. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  55054. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  55055. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  55056. }
  55057. this._buffer.update(this._vertexData);
  55058. // Render
  55059. var effect = this._effectBase;
  55060. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55061. effect = this._effectFog;
  55062. }
  55063. engine.enableEffect(effect);
  55064. var viewMatrix = this._scene.getViewMatrix();
  55065. effect.setTexture("diffuseSampler", this._spriteTexture);
  55066. effect.setMatrix("view", viewMatrix);
  55067. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55068. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  55069. // Fog
  55070. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  55071. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  55072. effect.setColor3("vFogColor", this._scene.fogColor);
  55073. }
  55074. // VBOs
  55075. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55076. // Draw order
  55077. engine.setDepthFunctionToLessOrEqual();
  55078. effect.setBool("alphaTest", true);
  55079. engine.setColorWrite(false);
  55080. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55081. engine.setColorWrite(true);
  55082. effect.setBool("alphaTest", false);
  55083. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55084. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  55085. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55086. };
  55087. SpriteManager.prototype.dispose = function () {
  55088. if (this._buffer) {
  55089. this._buffer.dispose();
  55090. this._buffer = null;
  55091. }
  55092. if (this._indexBuffer) {
  55093. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55094. this._indexBuffer = null;
  55095. }
  55096. if (this._spriteTexture) {
  55097. this._spriteTexture.dispose();
  55098. this._spriteTexture = null;
  55099. }
  55100. // Remove from scene
  55101. var index = this._scene.spriteManagers.indexOf(this);
  55102. this._scene.spriteManagers.splice(index, 1);
  55103. // Callback
  55104. this.onDisposeObservable.notifyObservers(this);
  55105. this.onDisposeObservable.clear();
  55106. };
  55107. return SpriteManager;
  55108. }());
  55109. BABYLON.SpriteManager = SpriteManager;
  55110. })(BABYLON || (BABYLON = {}));
  55111. //# sourceMappingURL=babylon.spriteManager.js.map
  55112. var BABYLON;
  55113. (function (BABYLON) {
  55114. var Sprite = /** @class */ (function () {
  55115. function Sprite(name, manager) {
  55116. this.name = name;
  55117. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55118. this.width = 1.0;
  55119. this.height = 1.0;
  55120. this.angle = 0;
  55121. this.cellIndex = 0;
  55122. this.invertU = 0;
  55123. this.invertV = 0;
  55124. this.animations = new Array();
  55125. this.isPickable = false;
  55126. this._animationStarted = false;
  55127. this._loopAnimation = false;
  55128. this._fromIndex = 0;
  55129. this._toIndex = 0;
  55130. this._delay = 0;
  55131. this._direction = 1;
  55132. this._time = 0;
  55133. /**
  55134. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  55135. */
  55136. this.isVisible = true;
  55137. this._manager = manager;
  55138. this._manager.sprites.push(this);
  55139. this.position = BABYLON.Vector3.Zero();
  55140. }
  55141. Object.defineProperty(Sprite.prototype, "size", {
  55142. get: function () {
  55143. return this.width;
  55144. },
  55145. set: function (value) {
  55146. this.width = value;
  55147. this.height = value;
  55148. },
  55149. enumerable: true,
  55150. configurable: true
  55151. });
  55152. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  55153. this._fromIndex = from;
  55154. this._toIndex = to;
  55155. this._loopAnimation = loop;
  55156. this._delay = delay;
  55157. this._animationStarted = true;
  55158. this._direction = from < to ? 1 : -1;
  55159. this.cellIndex = from;
  55160. this._time = 0;
  55161. this._onAnimationEnd = onAnimationEnd;
  55162. };
  55163. Sprite.prototype.stopAnimation = function () {
  55164. this._animationStarted = false;
  55165. };
  55166. /** @hidden */
  55167. Sprite.prototype._animate = function (deltaTime) {
  55168. if (!this._animationStarted)
  55169. return;
  55170. this._time += deltaTime;
  55171. if (this._time > this._delay) {
  55172. this._time = this._time % this._delay;
  55173. this.cellIndex += this._direction;
  55174. if (this.cellIndex > this._toIndex) {
  55175. if (this._loopAnimation) {
  55176. this.cellIndex = this._fromIndex;
  55177. }
  55178. else {
  55179. this.cellIndex = this._toIndex;
  55180. this._animationStarted = false;
  55181. if (this._onAnimationEnd) {
  55182. this._onAnimationEnd();
  55183. }
  55184. if (this.disposeWhenFinishedAnimating) {
  55185. this.dispose();
  55186. }
  55187. }
  55188. }
  55189. }
  55190. };
  55191. Sprite.prototype.dispose = function () {
  55192. for (var i = 0; i < this._manager.sprites.length; i++) {
  55193. if (this._manager.sprites[i] == this) {
  55194. this._manager.sprites.splice(i, 1);
  55195. }
  55196. }
  55197. };
  55198. return Sprite;
  55199. }());
  55200. BABYLON.Sprite = Sprite;
  55201. })(BABYLON || (BABYLON = {}));
  55202. //# sourceMappingURL=babylon.sprite.js.map
  55203. var BABYLON;
  55204. (function (BABYLON) {
  55205. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  55206. if (!BABYLON.PickingInfo) {
  55207. return null;
  55208. }
  55209. var pickingInfo = null;
  55210. if (!camera) {
  55211. if (!this.activeCamera) {
  55212. return null;
  55213. }
  55214. camera = this.activeCamera;
  55215. }
  55216. if (this.spriteManagers.length > 0) {
  55217. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  55218. var spriteManager = this.spriteManagers[spriteIndex];
  55219. if (!spriteManager.isPickable) {
  55220. continue;
  55221. }
  55222. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  55223. if (!result || !result.hit)
  55224. continue;
  55225. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  55226. continue;
  55227. pickingInfo = result;
  55228. if (fastCheck) {
  55229. break;
  55230. }
  55231. }
  55232. }
  55233. return pickingInfo || new BABYLON.PickingInfo();
  55234. };
  55235. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  55236. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  55237. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55238. };
  55239. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  55240. if (!this._tempSpritePickingRay) {
  55241. return null;
  55242. }
  55243. if (!camera) {
  55244. if (!this.activeCamera) {
  55245. return null;
  55246. }
  55247. camera = this.activeCamera;
  55248. }
  55249. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55250. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55251. };
  55252. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55253. if (this._pointerOverSprite === sprite) {
  55254. return;
  55255. }
  55256. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55257. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55258. }
  55259. this._pointerOverSprite = sprite;
  55260. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55261. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55262. }
  55263. };
  55264. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55265. return this._pointerOverSprite;
  55266. };
  55267. /**
  55268. * Defines the sprite scene component responsible to manage sprites
  55269. * in a given scene.
  55270. */
  55271. var SpriteSceneComponent = /** @class */ (function () {
  55272. /**
  55273. * Creates a new instance of the component for the given scene
  55274. * @param scene Defines the scene to register the component in
  55275. */
  55276. function SpriteSceneComponent(scene) {
  55277. /**
  55278. * The component name helpfull to identify the component in the list of scene components.
  55279. */
  55280. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55281. this.scene = scene;
  55282. this.scene.spriteManagers = new Array();
  55283. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55284. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55285. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55286. this._spritePredicate = function (sprite) {
  55287. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55288. };
  55289. }
  55290. /**
  55291. * Registers the component in a given scene
  55292. */
  55293. SpriteSceneComponent.prototype.register = function () {
  55294. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55295. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55296. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55297. };
  55298. /**
  55299. * Rebuilds the elements related to this component in case of
  55300. * context lost for instance.
  55301. */
  55302. SpriteSceneComponent.prototype.rebuild = function () {
  55303. /** Nothing to do for sprites */
  55304. };
  55305. /**
  55306. * Disposes the component and the associated ressources.
  55307. */
  55308. SpriteSceneComponent.prototype.dispose = function () {
  55309. this.scene.onBeforeSpritesRenderingObservable.clear();
  55310. this.scene.onAfterSpritesRenderingObservable.clear();
  55311. var spriteManagers = this.scene.spriteManagers;
  55312. while (spriteManagers.length) {
  55313. spriteManagers[0].dispose();
  55314. }
  55315. };
  55316. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55317. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55318. if (result) {
  55319. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55320. }
  55321. return result;
  55322. };
  55323. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55324. var scene = this.scene;
  55325. if (isMeshPicked) {
  55326. scene.setPointerOverSprite(null);
  55327. }
  55328. else {
  55329. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55330. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55331. scene.setPointerOverSprite(pickResult.pickedSprite);
  55332. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55333. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55334. }
  55335. else {
  55336. canvas.style.cursor = scene.hoverCursor;
  55337. }
  55338. }
  55339. else {
  55340. scene.setPointerOverSprite(null);
  55341. }
  55342. }
  55343. return pickResult;
  55344. };
  55345. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55346. var scene = this.scene;
  55347. scene._pickedDownSprite = null;
  55348. if (scene.spriteManagers.length > 0) {
  55349. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55350. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55351. if (pickResult.pickedSprite.actionManager) {
  55352. scene._pickedDownSprite = pickResult.pickedSprite;
  55353. switch (evt.button) {
  55354. case 0:
  55355. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55356. break;
  55357. case 1:
  55358. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55359. break;
  55360. case 2:
  55361. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55362. break;
  55363. }
  55364. if (pickResult.pickedSprite.actionManager) {
  55365. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55366. }
  55367. }
  55368. }
  55369. }
  55370. return pickResult;
  55371. };
  55372. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55373. var scene = this.scene;
  55374. if (scene.spriteManagers.length > 0) {
  55375. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55376. if (spritePickResult) {
  55377. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55378. if (spritePickResult.pickedSprite.actionManager) {
  55379. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55380. if (spritePickResult.pickedSprite.actionManager) {
  55381. if (!this.scene._isPointerSwiping()) {
  55382. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55383. }
  55384. }
  55385. }
  55386. }
  55387. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55388. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55389. }
  55390. }
  55391. }
  55392. return pickResult;
  55393. };
  55394. return SpriteSceneComponent;
  55395. }());
  55396. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55397. })(BABYLON || (BABYLON = {}));
  55398. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55399. var BABYLON;
  55400. (function (BABYLON) {
  55401. /**
  55402. * @hidden
  55403. */
  55404. var IntersectionInfo = /** @class */ (function () {
  55405. function IntersectionInfo(bu, bv, distance) {
  55406. this.bu = bu;
  55407. this.bv = bv;
  55408. this.distance = distance;
  55409. this.faceId = 0;
  55410. this.subMeshId = 0;
  55411. }
  55412. return IntersectionInfo;
  55413. }());
  55414. BABYLON.IntersectionInfo = IntersectionInfo;
  55415. /**
  55416. * Information about the result of picking within a scene
  55417. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  55418. */
  55419. var PickingInfo = /** @class */ (function () {
  55420. function PickingInfo() {
  55421. /**
  55422. * If the pick collided with an object
  55423. */
  55424. this.hit = false;
  55425. /**
  55426. * Distance away where the pick collided
  55427. */
  55428. this.distance = 0;
  55429. /**
  55430. * The location of pick collision
  55431. */
  55432. this.pickedPoint = null;
  55433. /**
  55434. * The mesh corresponding the the pick collision
  55435. */
  55436. this.pickedMesh = null;
  55437. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55438. this.bu = 0;
  55439. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55440. this.bv = 0;
  55441. /** The id of the face on the mesh that was picked */
  55442. this.faceId = -1;
  55443. /** Id of the the submesh that was picked */
  55444. this.subMeshId = 0;
  55445. /** If a sprite was picked, this will be the sprite the pick collided with */
  55446. this.pickedSprite = null;
  55447. /**
  55448. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55449. */
  55450. this.originMesh = null;
  55451. /**
  55452. * The ray that was used to perform the picking.
  55453. */
  55454. this.ray = null;
  55455. }
  55456. /**
  55457. * Gets the normal correspodning to the face the pick collided with
  55458. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55459. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55460. * @returns The normal correspodning to the face the pick collided with
  55461. */
  55462. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55463. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55464. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55465. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55466. return null;
  55467. }
  55468. var indices = this.pickedMesh.getIndices();
  55469. if (!indices) {
  55470. return null;
  55471. }
  55472. var result;
  55473. if (useVerticesNormals) {
  55474. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55475. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55476. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55477. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55478. normal0 = normal0.scale(this.bu);
  55479. normal1 = normal1.scale(this.bv);
  55480. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55481. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55482. }
  55483. else {
  55484. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55485. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55486. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55487. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55488. var p1p2 = vertex1.subtract(vertex2);
  55489. var p3p2 = vertex3.subtract(vertex2);
  55490. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55491. }
  55492. if (useWorldCoordinates) {
  55493. var wm = this.pickedMesh.getWorldMatrix();
  55494. if (this.pickedMesh.nonUniformScaling) {
  55495. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55496. wm = BABYLON.Tmp.Matrix[0];
  55497. wm.setTranslationFromFloats(0, 0, 0);
  55498. wm.invert();
  55499. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55500. wm = BABYLON.Tmp.Matrix[1];
  55501. }
  55502. result = BABYLON.Vector3.TransformNormal(result, wm);
  55503. }
  55504. result.normalize();
  55505. return result;
  55506. };
  55507. /**
  55508. * Gets the texture coordinates of where the pick occured
  55509. * @returns the vector containing the coordnates of the texture
  55510. */
  55511. PickingInfo.prototype.getTextureCoordinates = function () {
  55512. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55513. return null;
  55514. }
  55515. var indices = this.pickedMesh.getIndices();
  55516. if (!indices) {
  55517. return null;
  55518. }
  55519. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55520. if (!uvs) {
  55521. return null;
  55522. }
  55523. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55524. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55525. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55526. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55527. uv1 = uv1.scale(this.bu);
  55528. uv2 = uv2.scale(this.bv);
  55529. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55530. };
  55531. return PickingInfo;
  55532. }());
  55533. BABYLON.PickingInfo = PickingInfo;
  55534. })(BABYLON || (BABYLON = {}));
  55535. //# sourceMappingURL=babylon.pickingInfo.js.map
  55536. var BABYLON;
  55537. (function (BABYLON) {
  55538. var Ray = /** @class */ (function () {
  55539. function Ray(origin, direction, length) {
  55540. if (length === void 0) { length = Number.MAX_VALUE; }
  55541. this.origin = origin;
  55542. this.direction = direction;
  55543. this.length = length;
  55544. }
  55545. // Methods
  55546. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55547. var d = 0.0;
  55548. var maxValue = Number.MAX_VALUE;
  55549. var inv;
  55550. var min;
  55551. var max;
  55552. var temp;
  55553. if (Math.abs(this.direction.x) < 0.0000001) {
  55554. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55555. return false;
  55556. }
  55557. }
  55558. else {
  55559. inv = 1.0 / this.direction.x;
  55560. min = (minimum.x - this.origin.x) * inv;
  55561. max = (maximum.x - this.origin.x) * inv;
  55562. if (max === -Infinity) {
  55563. max = Infinity;
  55564. }
  55565. if (min > max) {
  55566. temp = min;
  55567. min = max;
  55568. max = temp;
  55569. }
  55570. d = Math.max(min, d);
  55571. maxValue = Math.min(max, maxValue);
  55572. if (d > maxValue) {
  55573. return false;
  55574. }
  55575. }
  55576. if (Math.abs(this.direction.y) < 0.0000001) {
  55577. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55578. return false;
  55579. }
  55580. }
  55581. else {
  55582. inv = 1.0 / this.direction.y;
  55583. min = (minimum.y - this.origin.y) * inv;
  55584. max = (maximum.y - this.origin.y) * inv;
  55585. if (max === -Infinity) {
  55586. max = Infinity;
  55587. }
  55588. if (min > max) {
  55589. temp = min;
  55590. min = max;
  55591. max = temp;
  55592. }
  55593. d = Math.max(min, d);
  55594. maxValue = Math.min(max, maxValue);
  55595. if (d > maxValue) {
  55596. return false;
  55597. }
  55598. }
  55599. if (Math.abs(this.direction.z) < 0.0000001) {
  55600. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55601. return false;
  55602. }
  55603. }
  55604. else {
  55605. inv = 1.0 / this.direction.z;
  55606. min = (minimum.z - this.origin.z) * inv;
  55607. max = (maximum.z - this.origin.z) * inv;
  55608. if (max === -Infinity) {
  55609. max = Infinity;
  55610. }
  55611. if (min > max) {
  55612. temp = min;
  55613. min = max;
  55614. max = temp;
  55615. }
  55616. d = Math.max(min, d);
  55617. maxValue = Math.min(max, maxValue);
  55618. if (d > maxValue) {
  55619. return false;
  55620. }
  55621. }
  55622. return true;
  55623. };
  55624. Ray.prototype.intersectsBox = function (box) {
  55625. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55626. };
  55627. Ray.prototype.intersectsSphere = function (sphere) {
  55628. var x = sphere.center.x - this.origin.x;
  55629. var y = sphere.center.y - this.origin.y;
  55630. var z = sphere.center.z - this.origin.z;
  55631. var pyth = (x * x) + (y * y) + (z * z);
  55632. var rr = sphere.radius * sphere.radius;
  55633. if (pyth <= rr) {
  55634. return true;
  55635. }
  55636. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55637. if (dot < 0.0) {
  55638. return false;
  55639. }
  55640. var temp = pyth - (dot * dot);
  55641. return temp <= rr;
  55642. };
  55643. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55644. if (!this._edge1) {
  55645. this._edge1 = BABYLON.Vector3.Zero();
  55646. this._edge2 = BABYLON.Vector3.Zero();
  55647. this._pvec = BABYLON.Vector3.Zero();
  55648. this._tvec = BABYLON.Vector3.Zero();
  55649. this._qvec = BABYLON.Vector3.Zero();
  55650. }
  55651. vertex1.subtractToRef(vertex0, this._edge1);
  55652. vertex2.subtractToRef(vertex0, this._edge2);
  55653. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55654. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55655. if (det === 0) {
  55656. return null;
  55657. }
  55658. var invdet = 1 / det;
  55659. this.origin.subtractToRef(vertex0, this._tvec);
  55660. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55661. if (bu < 0 || bu > 1.0) {
  55662. return null;
  55663. }
  55664. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55665. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55666. if (bv < 0 || bu + bv > 1.0) {
  55667. return null;
  55668. }
  55669. //check if the distance is longer than the predefined length.
  55670. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55671. if (distance > this.length) {
  55672. return null;
  55673. }
  55674. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55675. };
  55676. Ray.prototype.intersectsPlane = function (plane) {
  55677. var distance;
  55678. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55679. if (Math.abs(result1) < 9.99999997475243E-07) {
  55680. return null;
  55681. }
  55682. else {
  55683. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55684. distance = (-plane.d - result2) / result1;
  55685. if (distance < 0.0) {
  55686. if (distance < -9.99999997475243E-07) {
  55687. return null;
  55688. }
  55689. else {
  55690. return 0;
  55691. }
  55692. }
  55693. return distance;
  55694. }
  55695. };
  55696. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55697. var tm = BABYLON.Tmp.Matrix[0];
  55698. mesh.getWorldMatrix().invertToRef(tm);
  55699. if (this._tmpRay) {
  55700. Ray.TransformToRef(this, tm, this._tmpRay);
  55701. }
  55702. else {
  55703. this._tmpRay = Ray.Transform(this, tm);
  55704. }
  55705. return mesh.intersects(this._tmpRay, fastCheck);
  55706. };
  55707. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55708. if (results) {
  55709. results.length = 0;
  55710. }
  55711. else {
  55712. results = [];
  55713. }
  55714. for (var i = 0; i < meshes.length; i++) {
  55715. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55716. if (pickInfo.hit) {
  55717. results.push(pickInfo);
  55718. }
  55719. }
  55720. results.sort(this._comparePickingInfo);
  55721. return results;
  55722. };
  55723. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55724. if (pickingInfoA.distance < pickingInfoB.distance) {
  55725. return -1;
  55726. }
  55727. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55728. return 1;
  55729. }
  55730. else {
  55731. return 0;
  55732. }
  55733. };
  55734. /**
  55735. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55736. * @param sega the first point of the segment to test the intersection against
  55737. * @param segb the second point of the segment to test the intersection against
  55738. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55739. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55740. */
  55741. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55742. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55743. var u = segb.subtract(sega);
  55744. var v = rsegb.subtract(this.origin);
  55745. var w = sega.subtract(this.origin);
  55746. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55747. var b = BABYLON.Vector3.Dot(u, v);
  55748. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55749. var d = BABYLON.Vector3.Dot(u, w);
  55750. var e = BABYLON.Vector3.Dot(v, w);
  55751. var D = a * c - b * b; // always >= 0
  55752. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55753. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55754. // compute the line parameters of the two closest points
  55755. if (D < Ray.smallnum) { // the lines are almost parallel
  55756. sN = 0.0; // force using point P0 on segment S1
  55757. sD = 1.0; // to prevent possible division by 0.0 later
  55758. tN = e;
  55759. tD = c;
  55760. }
  55761. else { // get the closest points on the infinite lines
  55762. sN = (b * e - c * d);
  55763. tN = (a * e - b * d);
  55764. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55765. sN = 0.0;
  55766. tN = e;
  55767. tD = c;
  55768. }
  55769. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55770. sN = sD;
  55771. tN = e + b;
  55772. tD = c;
  55773. }
  55774. }
  55775. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55776. tN = 0.0;
  55777. // recompute sc for this edge
  55778. if (-d < 0.0) {
  55779. sN = 0.0;
  55780. }
  55781. else if (-d > a)
  55782. sN = sD;
  55783. else {
  55784. sN = -d;
  55785. sD = a;
  55786. }
  55787. }
  55788. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55789. tN = tD;
  55790. // recompute sc for this edge
  55791. if ((-d + b) < 0.0) {
  55792. sN = 0;
  55793. }
  55794. else if ((-d + b) > a) {
  55795. sN = sD;
  55796. }
  55797. else {
  55798. sN = (-d + b);
  55799. sD = a;
  55800. }
  55801. }
  55802. // finally do the division to get sc and tc
  55803. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55804. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55805. // get the difference of the two closest points
  55806. var qtc = v.multiplyByFloats(tc, tc, tc);
  55807. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55808. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55809. if (isIntersected) {
  55810. return qtc.length();
  55811. }
  55812. return -1;
  55813. };
  55814. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55815. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55816. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55817. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55818. this.direction.normalize();
  55819. return this;
  55820. };
  55821. // Statics
  55822. Ray.Zero = function () {
  55823. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55824. };
  55825. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55826. var result = Ray.Zero();
  55827. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55828. };
  55829. /**
  55830. * 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
  55831. * transformed to the given world matrix.
  55832. * @param origin The origin point
  55833. * @param end The end point
  55834. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55835. */
  55836. Ray.CreateNewFromTo = function (origin, end, world) {
  55837. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55838. var direction = end.subtract(origin);
  55839. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55840. direction.normalize();
  55841. return Ray.Transform(new Ray(origin, direction, length), world);
  55842. };
  55843. Ray.Transform = function (ray, matrix) {
  55844. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55845. Ray.TransformToRef(ray, matrix, result);
  55846. return result;
  55847. };
  55848. Ray.TransformToRef = function (ray, matrix, result) {
  55849. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55850. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55851. result.length = ray.length;
  55852. var dir = result.direction;
  55853. var len = dir.length();
  55854. if (!(len === 0 || len === 1)) {
  55855. var num = 1.0 / len;
  55856. dir.x *= num;
  55857. dir.y *= num;
  55858. dir.z *= num;
  55859. result.length *= len;
  55860. }
  55861. };
  55862. Ray.smallnum = 0.00000001;
  55863. Ray.rayl = 10e8;
  55864. return Ray;
  55865. }());
  55866. BABYLON.Ray = Ray;
  55867. })(BABYLON || (BABYLON = {}));
  55868. //# sourceMappingURL=babylon.ray.js.map
  55869. var BABYLON;
  55870. (function (BABYLON) {
  55871. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55872. if (boxMin.x > sphereCenter.x + sphereRadius)
  55873. return false;
  55874. if (sphereCenter.x - sphereRadius > boxMax.x)
  55875. return false;
  55876. if (boxMin.y > sphereCenter.y + sphereRadius)
  55877. return false;
  55878. if (sphereCenter.y - sphereRadius > boxMax.y)
  55879. return false;
  55880. if (boxMin.z > sphereCenter.z + sphereRadius)
  55881. return false;
  55882. if (sphereCenter.z - sphereRadius > boxMax.z)
  55883. return false;
  55884. return true;
  55885. };
  55886. var getLowestRoot = (function () {
  55887. var result = { root: 0, found: false };
  55888. return function (a, b, c, maxR) {
  55889. result.root = 0;
  55890. result.found = false;
  55891. var determinant = b * b - 4.0 * a * c;
  55892. if (determinant < 0)
  55893. return result;
  55894. var sqrtD = Math.sqrt(determinant);
  55895. var r1 = (-b - sqrtD) / (2.0 * a);
  55896. var r2 = (-b + sqrtD) / (2.0 * a);
  55897. if (r1 > r2) {
  55898. var temp = r2;
  55899. r2 = r1;
  55900. r1 = temp;
  55901. }
  55902. if (r1 > 0 && r1 < maxR) {
  55903. result.root = r1;
  55904. result.found = true;
  55905. return result;
  55906. }
  55907. if (r2 > 0 && r2 < maxR) {
  55908. result.root = r2;
  55909. result.found = true;
  55910. return result;
  55911. }
  55912. return result;
  55913. };
  55914. })();
  55915. /** @hidden */
  55916. var Collider = /** @class */ (function () {
  55917. function Collider() {
  55918. this._collisionPoint = BABYLON.Vector3.Zero();
  55919. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55920. this._tempVector = BABYLON.Vector3.Zero();
  55921. this._tempVector2 = BABYLON.Vector3.Zero();
  55922. this._tempVector3 = BABYLON.Vector3.Zero();
  55923. this._tempVector4 = BABYLON.Vector3.Zero();
  55924. this._edge = BABYLON.Vector3.Zero();
  55925. this._baseToVertex = BABYLON.Vector3.Zero();
  55926. this._destinationPoint = BABYLON.Vector3.Zero();
  55927. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55928. this._displacementVector = BABYLON.Vector3.Zero();
  55929. /** @hidden */
  55930. this._radius = BABYLON.Vector3.One();
  55931. /** @hidden */
  55932. this._retry = 0;
  55933. /** @hidden */
  55934. this._basePointWorld = BABYLON.Vector3.Zero();
  55935. this._velocityWorld = BABYLON.Vector3.Zero();
  55936. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55937. this._collisionMask = -1;
  55938. }
  55939. Object.defineProperty(Collider.prototype, "collisionMask", {
  55940. get: function () {
  55941. return this._collisionMask;
  55942. },
  55943. set: function (mask) {
  55944. this._collisionMask = !isNaN(mask) ? mask : -1;
  55945. },
  55946. enumerable: true,
  55947. configurable: true
  55948. });
  55949. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55950. /**
  55951. * Gets the plane normal used to compute the sliding response (in local space)
  55952. */
  55953. get: function () {
  55954. return this._slidePlaneNormal;
  55955. },
  55956. enumerable: true,
  55957. configurable: true
  55958. });
  55959. // Methods
  55960. /** @hidden */
  55961. Collider.prototype._initialize = function (source, dir, e) {
  55962. this._velocity = dir;
  55963. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55964. this._basePoint = source;
  55965. source.multiplyToRef(this._radius, this._basePointWorld);
  55966. dir.multiplyToRef(this._radius, this._velocityWorld);
  55967. this._velocityWorldLength = this._velocityWorld.length();
  55968. this._epsilon = e;
  55969. this.collisionFound = false;
  55970. };
  55971. /** @hidden */
  55972. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55973. pa.subtractToRef(point, this._tempVector);
  55974. pb.subtractToRef(point, this._tempVector2);
  55975. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55976. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55977. if (d < 0)
  55978. return false;
  55979. pc.subtractToRef(point, this._tempVector3);
  55980. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55981. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55982. if (d < 0)
  55983. return false;
  55984. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55985. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55986. return d >= 0;
  55987. };
  55988. /** @hidden */
  55989. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55990. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55991. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55992. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55993. return false;
  55994. }
  55995. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55996. return false;
  55997. return true;
  55998. };
  55999. /** @hidden */
  56000. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56001. var t0;
  56002. var embeddedInPlane = false;
  56003. //defensive programming, actually not needed.
  56004. if (!trianglePlaneArray) {
  56005. trianglePlaneArray = [];
  56006. }
  56007. if (!trianglePlaneArray[faceIndex]) {
  56008. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56009. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56010. }
  56011. var trianglePlane = trianglePlaneArray[faceIndex];
  56012. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56013. return;
  56014. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56015. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56016. if (normalDotVelocity == 0) {
  56017. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  56018. return;
  56019. embeddedInPlane = true;
  56020. t0 = 0;
  56021. }
  56022. else {
  56023. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56024. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  56025. if (t0 > t1) {
  56026. var temp = t1;
  56027. t1 = t0;
  56028. t0 = temp;
  56029. }
  56030. if (t0 > 1.0 || t1 < 0.0)
  56031. return;
  56032. if (t0 < 0)
  56033. t0 = 0;
  56034. if (t0 > 1.0)
  56035. t0 = 1.0;
  56036. }
  56037. this._collisionPoint.copyFromFloats(0, 0, 0);
  56038. var found = false;
  56039. var t = 1.0;
  56040. if (!embeddedInPlane) {
  56041. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  56042. this._velocity.scaleToRef(t0, this._tempVector);
  56043. this._planeIntersectionPoint.addInPlace(this._tempVector);
  56044. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  56045. found = true;
  56046. t = t0;
  56047. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  56048. }
  56049. }
  56050. if (!found) {
  56051. var velocitySquaredLength = this._velocity.lengthSquared();
  56052. var a = velocitySquaredLength;
  56053. this._basePoint.subtractToRef(p1, this._tempVector);
  56054. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56055. var c = this._tempVector.lengthSquared() - 1.0;
  56056. var lowestRoot = getLowestRoot(a, b, c, t);
  56057. if (lowestRoot.found) {
  56058. t = lowestRoot.root;
  56059. found = true;
  56060. this._collisionPoint.copyFrom(p1);
  56061. }
  56062. this._basePoint.subtractToRef(p2, this._tempVector);
  56063. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56064. c = this._tempVector.lengthSquared() - 1.0;
  56065. lowestRoot = getLowestRoot(a, b, c, t);
  56066. if (lowestRoot.found) {
  56067. t = lowestRoot.root;
  56068. found = true;
  56069. this._collisionPoint.copyFrom(p2);
  56070. }
  56071. this._basePoint.subtractToRef(p3, this._tempVector);
  56072. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  56073. c = this._tempVector.lengthSquared() - 1.0;
  56074. lowestRoot = getLowestRoot(a, b, c, t);
  56075. if (lowestRoot.found) {
  56076. t = lowestRoot.root;
  56077. found = true;
  56078. this._collisionPoint.copyFrom(p3);
  56079. }
  56080. p2.subtractToRef(p1, this._edge);
  56081. p1.subtractToRef(this._basePoint, this._baseToVertex);
  56082. var edgeSquaredLength = this._edge.lengthSquared();
  56083. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56084. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56085. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56086. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56087. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56088. lowestRoot = getLowestRoot(a, b, c, t);
  56089. if (lowestRoot.found) {
  56090. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56091. if (f >= 0.0 && f <= 1.0) {
  56092. t = lowestRoot.root;
  56093. found = true;
  56094. this._edge.scaleInPlace(f);
  56095. p1.addToRef(this._edge, this._collisionPoint);
  56096. }
  56097. }
  56098. p3.subtractToRef(p2, this._edge);
  56099. p2.subtractToRef(this._basePoint, this._baseToVertex);
  56100. edgeSquaredLength = this._edge.lengthSquared();
  56101. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56102. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56103. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56104. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56105. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56106. lowestRoot = getLowestRoot(a, b, c, t);
  56107. if (lowestRoot.found) {
  56108. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56109. if (f >= 0.0 && f <= 1.0) {
  56110. t = lowestRoot.root;
  56111. found = true;
  56112. this._edge.scaleInPlace(f);
  56113. p2.addToRef(this._edge, this._collisionPoint);
  56114. }
  56115. }
  56116. p1.subtractToRef(p3, this._edge);
  56117. p3.subtractToRef(this._basePoint, this._baseToVertex);
  56118. edgeSquaredLength = this._edge.lengthSquared();
  56119. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  56120. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  56121. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  56122. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  56123. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  56124. lowestRoot = getLowestRoot(a, b, c, t);
  56125. if (lowestRoot.found) {
  56126. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  56127. if (f >= 0.0 && f <= 1.0) {
  56128. t = lowestRoot.root;
  56129. found = true;
  56130. this._edge.scaleInPlace(f);
  56131. p3.addToRef(this._edge, this._collisionPoint);
  56132. }
  56133. }
  56134. }
  56135. if (found) {
  56136. var distToCollision = t * this._velocity.length();
  56137. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  56138. if (!this.intersectionPoint) {
  56139. this.intersectionPoint = this._collisionPoint.clone();
  56140. }
  56141. else {
  56142. this.intersectionPoint.copyFrom(this._collisionPoint);
  56143. }
  56144. this._nearestDistance = distToCollision;
  56145. this.collisionFound = true;
  56146. }
  56147. }
  56148. };
  56149. /** @hidden */
  56150. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  56151. for (var i = indexStart; i < indexEnd; i += 3) {
  56152. var p1 = pts[indices[i] - decal];
  56153. var p2 = pts[indices[i + 1] - decal];
  56154. var p3 = pts[indices[i + 2] - decal];
  56155. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  56156. }
  56157. };
  56158. /** @hidden */
  56159. Collider.prototype._getResponse = function (pos, vel) {
  56160. pos.addToRef(vel, this._destinationPoint);
  56161. vel.scaleInPlace((this._nearestDistance / vel.length()));
  56162. this._basePoint.addToRef(vel, pos);
  56163. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  56164. this._slidePlaneNormal.normalize();
  56165. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  56166. pos.addInPlace(this._displacementVector);
  56167. this.intersectionPoint.addInPlace(this._displacementVector);
  56168. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  56169. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  56170. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  56171. };
  56172. return Collider;
  56173. }());
  56174. BABYLON.Collider = Collider;
  56175. })(BABYLON || (BABYLON = {}));
  56176. //# sourceMappingURL=babylon.collider.js.map
  56177. var BABYLON;
  56178. (function (BABYLON) {
  56179. //WebWorker code will be inserted to this variable.
  56180. /** @hidden */
  56181. BABYLON.CollisionWorker = "";
  56182. /** Defines supported task for worker process */
  56183. var WorkerTaskType;
  56184. (function (WorkerTaskType) {
  56185. /** Initialization */
  56186. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  56187. /** Update of geometry */
  56188. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  56189. /** Evaluate collision */
  56190. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  56191. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  56192. /** Defines kind of replies returned by worker */
  56193. var WorkerReplyType;
  56194. (function (WorkerReplyType) {
  56195. /** Success */
  56196. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  56197. /** Unkown error */
  56198. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  56199. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  56200. /** @hidden */
  56201. var CollisionCoordinatorWorker = /** @class */ (function () {
  56202. function CollisionCoordinatorWorker() {
  56203. var _this = this;
  56204. this._scaledPosition = BABYLON.Vector3.Zero();
  56205. this._scaledVelocity = BABYLON.Vector3.Zero();
  56206. this.onMeshUpdated = function (transformNode) {
  56207. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  56208. };
  56209. this.onGeometryUpdated = function (geometry) {
  56210. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  56211. };
  56212. this._afterRender = function () {
  56213. if (!_this._init)
  56214. return;
  56215. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  56216. return;
  56217. }
  56218. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  56219. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  56220. if (_this._runningUpdated > 4) {
  56221. return;
  56222. }
  56223. ++_this._runningUpdated;
  56224. var payload = {
  56225. updatedMeshes: _this._addUpdateMeshesList,
  56226. updatedGeometries: _this._addUpdateGeometriesList,
  56227. removedGeometries: _this._toRemoveGeometryArray,
  56228. removedMeshes: _this._toRemoveMeshesArray
  56229. };
  56230. var message = {
  56231. payload: payload,
  56232. taskType: WorkerTaskType.UPDATE
  56233. };
  56234. var serializable = [];
  56235. for (var id in payload.updatedGeometries) {
  56236. if (payload.updatedGeometries.hasOwnProperty(id)) {
  56237. //prepare transferables
  56238. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  56239. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  56240. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  56241. }
  56242. }
  56243. _this._worker.postMessage(message, serializable);
  56244. _this._addUpdateMeshesList = {};
  56245. _this._addUpdateGeometriesList = {};
  56246. _this._toRemoveGeometryArray = [];
  56247. _this._toRemoveMeshesArray = [];
  56248. };
  56249. this._onMessageFromWorker = function (e) {
  56250. var returnData = e.data;
  56251. if (returnData.error != WorkerReplyType.SUCCESS) {
  56252. //TODO what errors can be returned from the worker?
  56253. BABYLON.Tools.Warn("error returned from worker!");
  56254. return;
  56255. }
  56256. switch (returnData.taskType) {
  56257. case WorkerTaskType.INIT:
  56258. _this._init = true;
  56259. //Update the worked with ALL of the scene's current state
  56260. _this._scene.meshes.forEach(function (mesh) {
  56261. _this.onMeshAdded(mesh);
  56262. });
  56263. _this._scene.getGeometries().forEach(function (geometry) {
  56264. _this.onGeometryAdded(geometry);
  56265. });
  56266. break;
  56267. case WorkerTaskType.UPDATE:
  56268. _this._runningUpdated--;
  56269. break;
  56270. case WorkerTaskType.COLLIDE:
  56271. var returnPayload = returnData.payload;
  56272. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56273. return;
  56274. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56275. if (callback) {
  56276. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56277. if (mesh) {
  56278. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56279. }
  56280. }
  56281. //cleanup
  56282. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56283. break;
  56284. }
  56285. };
  56286. this._collisionsCallbackArray = [];
  56287. this._init = false;
  56288. this._runningUpdated = 0;
  56289. this._addUpdateMeshesList = {};
  56290. this._addUpdateGeometriesList = {};
  56291. this._toRemoveGeometryArray = [];
  56292. this._toRemoveMeshesArray = [];
  56293. }
  56294. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56295. if (!this._init)
  56296. return;
  56297. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56298. return;
  56299. position.divideToRef(collider._radius, this._scaledPosition);
  56300. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56301. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56302. var payload = {
  56303. collider: {
  56304. position: this._scaledPosition.asArray(),
  56305. velocity: this._scaledVelocity.asArray(),
  56306. radius: collider._radius.asArray()
  56307. },
  56308. collisionId: collisionIndex,
  56309. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56310. maximumRetry: maximumRetry
  56311. };
  56312. var message = {
  56313. payload: payload,
  56314. taskType: WorkerTaskType.COLLIDE
  56315. };
  56316. this._worker.postMessage(message);
  56317. };
  56318. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56319. this._scene = scene;
  56320. this._scene.registerAfterRender(this._afterRender);
  56321. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56322. this._worker = new Worker(workerUrl);
  56323. this._worker.onmessage = this._onMessageFromWorker;
  56324. var message = {
  56325. payload: {},
  56326. taskType: WorkerTaskType.INIT
  56327. };
  56328. this._worker.postMessage(message);
  56329. };
  56330. CollisionCoordinatorWorker.prototype.destroy = function () {
  56331. this._scene.unregisterAfterRender(this._afterRender);
  56332. this._worker.terminate();
  56333. };
  56334. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56335. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56336. this.onMeshUpdated(mesh);
  56337. };
  56338. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56339. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56340. };
  56341. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56342. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56343. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56344. this.onGeometryUpdated(geometry);
  56345. };
  56346. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56347. this._toRemoveGeometryArray.push(geometry.id);
  56348. };
  56349. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56350. var submeshes = [];
  56351. if (mesh.subMeshes) {
  56352. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56353. var boundingInfo = sm.getBoundingInfo();
  56354. return {
  56355. position: idx,
  56356. verticesStart: sm.verticesStart,
  56357. verticesCount: sm.verticesCount,
  56358. indexStart: sm.indexStart,
  56359. indexCount: sm.indexCount,
  56360. hasMaterial: !!sm.getMaterial(),
  56361. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56362. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56363. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56364. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56365. };
  56366. });
  56367. }
  56368. var geometryId = null;
  56369. if (mesh instanceof BABYLON.Mesh) {
  56370. var geometry = mesh.geometry;
  56371. geometryId = geometry ? geometry.id : null;
  56372. }
  56373. else if (mesh instanceof BABYLON.InstancedMesh) {
  56374. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56375. geometryId = geometry ? geometry.id : null;
  56376. }
  56377. var boundingInfo = mesh.getBoundingInfo();
  56378. return {
  56379. uniqueId: mesh.uniqueId,
  56380. id: mesh.id,
  56381. name: mesh.name,
  56382. geometryId: geometryId,
  56383. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56384. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56385. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56386. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56387. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56388. subMeshes: submeshes,
  56389. checkCollisions: mesh.checkCollisions
  56390. };
  56391. };
  56392. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56393. return {
  56394. id: geometry.id,
  56395. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56396. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56397. indices: new Uint32Array(geometry.getIndices() || []),
  56398. };
  56399. };
  56400. return CollisionCoordinatorWorker;
  56401. }());
  56402. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56403. /** @hidden */
  56404. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56405. function CollisionCoordinatorLegacy() {
  56406. this._scaledPosition = BABYLON.Vector3.Zero();
  56407. this._scaledVelocity = BABYLON.Vector3.Zero();
  56408. this._finalPosition = BABYLON.Vector3.Zero();
  56409. }
  56410. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56411. position.divideToRef(collider._radius, this._scaledPosition);
  56412. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56413. collider.collidedMesh = null;
  56414. collider._retry = 0;
  56415. collider._initialVelocity = this._scaledVelocity;
  56416. collider._initialPosition = this._scaledPosition;
  56417. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56418. this._finalPosition.multiplyInPlace(collider._radius);
  56419. //run the callback
  56420. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56421. };
  56422. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56423. this._scene = scene;
  56424. };
  56425. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56426. //Legacy need no destruction method.
  56427. };
  56428. //No update in legacy mode
  56429. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56430. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56431. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56432. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56433. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56434. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56435. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56436. if (excludedMesh === void 0) { excludedMesh = null; }
  56437. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56438. if (collider._retry >= maximumRetry) {
  56439. finalPosition.copyFrom(position);
  56440. return;
  56441. }
  56442. // Check if this is a mesh else camera or -1
  56443. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56444. collider._initialize(position, velocity, closeDistance);
  56445. // Check all meshes
  56446. for (var index = 0; index < this._scene.meshes.length; index++) {
  56447. var mesh = this._scene.meshes[index];
  56448. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56449. mesh._checkCollision(collider);
  56450. }
  56451. }
  56452. if (!collider.collisionFound) {
  56453. position.addToRef(velocity, finalPosition);
  56454. return;
  56455. }
  56456. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56457. collider._getResponse(position, velocity);
  56458. }
  56459. if (velocity.length() <= closeDistance) {
  56460. finalPosition.copyFrom(position);
  56461. return;
  56462. }
  56463. collider._retry++;
  56464. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56465. };
  56466. return CollisionCoordinatorLegacy;
  56467. }());
  56468. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56469. })(BABYLON || (BABYLON = {}));
  56470. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56471. var BABYLON;
  56472. (function (BABYLON) {
  56473. /**
  56474. * A particle represents one of the element emitted by a particle system.
  56475. * This is mainly define by its coordinates, direction, velocity and age.
  56476. */
  56477. var Particle = /** @class */ (function () {
  56478. /**
  56479. * Creates a new instance Particle
  56480. * @param particleSystem the particle system the particle belongs to
  56481. */
  56482. function Particle(
  56483. /**
  56484. * The particle system the particle belongs to.
  56485. */
  56486. particleSystem) {
  56487. this.particleSystem = particleSystem;
  56488. /**
  56489. * The world position of the particle in the scene.
  56490. */
  56491. this.position = BABYLON.Vector3.Zero();
  56492. /**
  56493. * The world direction of the particle in the scene.
  56494. */
  56495. this.direction = BABYLON.Vector3.Zero();
  56496. /**
  56497. * The color of the particle.
  56498. */
  56499. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56500. /**
  56501. * The color change of the particle per step.
  56502. */
  56503. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56504. /**
  56505. * Defines how long will the life of the particle be.
  56506. */
  56507. this.lifeTime = 1.0;
  56508. /**
  56509. * The current age of the particle.
  56510. */
  56511. this.age = 0;
  56512. /**
  56513. * The current size of the particle.
  56514. */
  56515. this.size = 0;
  56516. /**
  56517. * The current scale of the particle.
  56518. */
  56519. this.scale = new BABYLON.Vector2(1, 1);
  56520. /**
  56521. * The current angle of the particle.
  56522. */
  56523. this.angle = 0;
  56524. /**
  56525. * Defines how fast is the angle changing.
  56526. */
  56527. this.angularSpeed = 0;
  56528. /**
  56529. * Defines the cell index used by the particle to be rendered from a sprite.
  56530. */
  56531. this.cellIndex = 0;
  56532. /** @hidden */
  56533. this._attachedSubEmitters = null;
  56534. /** @hidden */
  56535. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56536. /** @hidden */
  56537. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56538. /** @hidden */
  56539. this._currentSize1 = 0;
  56540. /** @hidden */
  56541. this._currentSize2 = 0;
  56542. /** @hidden */
  56543. this._currentAngularSpeed1 = 0;
  56544. /** @hidden */
  56545. this._currentAngularSpeed2 = 0;
  56546. /** @hidden */
  56547. this._currentVelocity1 = 0;
  56548. /** @hidden */
  56549. this._currentVelocity2 = 0;
  56550. /** @hidden */
  56551. this._currentLimitVelocity1 = 0;
  56552. /** @hidden */
  56553. this._currentLimitVelocity2 = 0;
  56554. /** @hidden */
  56555. this._currentDrag1 = 0;
  56556. /** @hidden */
  56557. this._currentDrag2 = 0;
  56558. this.id = Particle._Count++;
  56559. if (!this.particleSystem.isAnimationSheetEnabled) {
  56560. return;
  56561. }
  56562. this.updateCellInfoFromSystem();
  56563. }
  56564. Particle.prototype.updateCellInfoFromSystem = function () {
  56565. this.cellIndex = this.particleSystem.startSpriteCellID;
  56566. };
  56567. /**
  56568. * Defines how the sprite cell index is updated for the particle
  56569. */
  56570. Particle.prototype.updateCellIndex = function () {
  56571. var offsetAge = this.age;
  56572. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56573. if (this.particleSystem.spriteRandomStartCell) {
  56574. if (this._randomCellOffset === undefined) {
  56575. this._randomCellOffset = Math.random() * this.lifeTime;
  56576. }
  56577. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56578. changeSpeed = 1;
  56579. offsetAge = this._randomCellOffset;
  56580. }
  56581. else {
  56582. offsetAge += this._randomCellOffset;
  56583. }
  56584. }
  56585. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56586. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56587. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56588. };
  56589. /** @hidden */
  56590. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56591. if (subEmitter.particleSystem.emitter.position) {
  56592. var emitterMesh = subEmitter.particleSystem.emitter;
  56593. emitterMesh.position.copyFrom(this.position);
  56594. if (subEmitter.inheritDirection) {
  56595. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56596. // Look at using Y as forward
  56597. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56598. }
  56599. }
  56600. else {
  56601. var emitterPosition = subEmitter.particleSystem.emitter;
  56602. emitterPosition.copyFrom(this.position);
  56603. }
  56604. // Set inheritedVelocityOffset to be used when new particles are created
  56605. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56606. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56607. };
  56608. /** @hidden */
  56609. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56610. var _this = this;
  56611. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56612. this._attachedSubEmitters.forEach(function (subEmitter) {
  56613. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56614. });
  56615. }
  56616. };
  56617. /** @hidden */
  56618. Particle.prototype._reset = function () {
  56619. this.age = 0;
  56620. this._currentColorGradient = null;
  56621. this._currentSizeGradient = null;
  56622. this._currentAngularSpeedGradient = null;
  56623. this._currentVelocityGradient = null;
  56624. this._currentLimitVelocityGradient = null;
  56625. this._currentDragGradient = null;
  56626. this.cellIndex = this.particleSystem.startSpriteCellID;
  56627. this._randomCellOffset = undefined;
  56628. };
  56629. /**
  56630. * Copy the properties of particle to another one.
  56631. * @param other the particle to copy the information to.
  56632. */
  56633. Particle.prototype.copyTo = function (other) {
  56634. other.position.copyFrom(this.position);
  56635. if (this._initialDirection) {
  56636. if (other._initialDirection) {
  56637. other._initialDirection.copyFrom(this._initialDirection);
  56638. }
  56639. else {
  56640. other._initialDirection = this._initialDirection.clone();
  56641. }
  56642. }
  56643. else {
  56644. other._initialDirection = null;
  56645. }
  56646. other.direction.copyFrom(this.direction);
  56647. other.color.copyFrom(this.color);
  56648. other.colorStep.copyFrom(this.colorStep);
  56649. other.lifeTime = this.lifeTime;
  56650. other.age = this.age;
  56651. other._randomCellOffset = this._randomCellOffset;
  56652. other.size = this.size;
  56653. other.scale.copyFrom(this.scale);
  56654. other.angle = this.angle;
  56655. other.angularSpeed = this.angularSpeed;
  56656. other.particleSystem = this.particleSystem;
  56657. other.cellIndex = this.cellIndex;
  56658. other.id = this.id;
  56659. other._attachedSubEmitters = this._attachedSubEmitters;
  56660. if (this._currentColorGradient) {
  56661. other._currentColorGradient = this._currentColorGradient;
  56662. other._currentColor1.copyFrom(this._currentColor1);
  56663. other._currentColor2.copyFrom(this._currentColor2);
  56664. }
  56665. if (this._currentSizeGradient) {
  56666. other._currentSizeGradient = this._currentSizeGradient;
  56667. other._currentSize1 = this._currentSize1;
  56668. other._currentSize2 = this._currentSize2;
  56669. }
  56670. if (this._currentAngularSpeedGradient) {
  56671. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56672. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56673. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56674. }
  56675. if (this._currentVelocityGradient) {
  56676. other._currentVelocityGradient = this._currentVelocityGradient;
  56677. other._currentVelocity1 = this._currentVelocity1;
  56678. other._currentVelocity2 = this._currentVelocity2;
  56679. }
  56680. if (this._currentLimitVelocityGradient) {
  56681. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56682. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56683. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56684. }
  56685. if (this._currentDragGradient) {
  56686. other._currentDragGradient = this._currentDragGradient;
  56687. other._currentDrag1 = this._currentDrag1;
  56688. other._currentDrag2 = this._currentDrag2;
  56689. }
  56690. if (this.particleSystem.isAnimationSheetEnabled) {
  56691. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56692. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56693. }
  56694. if (this.particleSystem.useRampGradients) {
  56695. other.remapData.copyFrom(this.remapData);
  56696. }
  56697. if (this._randomNoiseCoordinates1) {
  56698. if (other._randomNoiseCoordinates1) {
  56699. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56700. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56701. }
  56702. else {
  56703. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56704. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56705. }
  56706. }
  56707. };
  56708. Particle._Count = 0;
  56709. return Particle;
  56710. }());
  56711. BABYLON.Particle = Particle;
  56712. })(BABYLON || (BABYLON = {}));
  56713. //# sourceMappingURL=babylon.particle.js.map
  56714. var BABYLON;
  56715. (function (BABYLON) {
  56716. /**
  56717. * This represents the base class for particle system in Babylon.
  56718. * 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.
  56719. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56720. * @example https://doc.babylonjs.com/babylon101/particles
  56721. */
  56722. var BaseParticleSystem = /** @class */ (function () {
  56723. /**
  56724. * Instantiates a particle system.
  56725. * 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.
  56726. * @param name The name of the particle system
  56727. */
  56728. function BaseParticleSystem(name) {
  56729. /**
  56730. * List of animations used by the particle system.
  56731. */
  56732. this.animations = [];
  56733. /**
  56734. * The rendering group used by the Particle system to chose when to render.
  56735. */
  56736. this.renderingGroupId = 0;
  56737. /**
  56738. * The emitter represents the Mesh or position we are attaching the particle system to.
  56739. */
  56740. this.emitter = null;
  56741. /**
  56742. * The maximum number of particles to emit per frame
  56743. */
  56744. this.emitRate = 10;
  56745. /**
  56746. * If you want to launch only a few particles at once, that can be done, as well.
  56747. */
  56748. this.manualEmitCount = -1;
  56749. /**
  56750. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56751. */
  56752. this.updateSpeed = 0.01;
  56753. /**
  56754. * The amount of time the particle system is running (depends of the overall update speed).
  56755. */
  56756. this.targetStopDuration = 0;
  56757. /**
  56758. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56759. */
  56760. this.disposeOnStop = false;
  56761. /**
  56762. * Minimum power of emitting particles.
  56763. */
  56764. this.minEmitPower = 1;
  56765. /**
  56766. * Maximum power of emitting particles.
  56767. */
  56768. this.maxEmitPower = 1;
  56769. /**
  56770. * Minimum life time of emitting particles.
  56771. */
  56772. this.minLifeTime = 1;
  56773. /**
  56774. * Maximum life time of emitting particles.
  56775. */
  56776. this.maxLifeTime = 1;
  56777. /**
  56778. * Minimum Size of emitting particles.
  56779. */
  56780. this.minSize = 1;
  56781. /**
  56782. * Maximum Size of emitting particles.
  56783. */
  56784. this.maxSize = 1;
  56785. /**
  56786. * Minimum scale of emitting particles on X axis.
  56787. */
  56788. this.minScaleX = 1;
  56789. /**
  56790. * Maximum scale of emitting particles on X axis.
  56791. */
  56792. this.maxScaleX = 1;
  56793. /**
  56794. * Minimum scale of emitting particles on Y axis.
  56795. */
  56796. this.minScaleY = 1;
  56797. /**
  56798. * Maximum scale of emitting particles on Y axis.
  56799. */
  56800. this.maxScaleY = 1;
  56801. /**
  56802. * Gets or sets the minimal initial rotation in radians.
  56803. */
  56804. this.minInitialRotation = 0;
  56805. /**
  56806. * Gets or sets the maximal initial rotation in radians.
  56807. */
  56808. this.maxInitialRotation = 0;
  56809. /**
  56810. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56811. */
  56812. this.minAngularSpeed = 0;
  56813. /**
  56814. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56815. */
  56816. this.maxAngularSpeed = 0;
  56817. /**
  56818. * The layer mask we are rendering the particles through.
  56819. */
  56820. this.layerMask = 0x0FFFFFFF;
  56821. /**
  56822. * This can help using your own shader to render the particle system.
  56823. * The according effect will be created
  56824. */
  56825. this.customShader = null;
  56826. /**
  56827. * By default particle system starts as soon as they are created. This prevents the
  56828. * automatic start to happen and let you decide when to start emitting particles.
  56829. */
  56830. this.preventAutoStart = false;
  56831. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56832. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56833. /**
  56834. * Callback triggered when the particle animation is ending.
  56835. */
  56836. this.onAnimationEnd = null;
  56837. /**
  56838. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56839. */
  56840. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56841. /**
  56842. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56843. * to override the particles.
  56844. */
  56845. this.forceDepthWrite = false;
  56846. /** 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 */
  56847. this.preWarmCycles = 0;
  56848. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56849. this.preWarmStepOffset = 1;
  56850. /**
  56851. * 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)
  56852. */
  56853. this.spriteCellChangeSpeed = 1;
  56854. /**
  56855. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56856. */
  56857. this.startSpriteCellID = 0;
  56858. /**
  56859. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56860. */
  56861. this.endSpriteCellID = 0;
  56862. /**
  56863. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56864. */
  56865. this.spriteCellWidth = 0;
  56866. /**
  56867. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56868. */
  56869. this.spriteCellHeight = 0;
  56870. /**
  56871. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56872. */
  56873. this.spriteRandomStartCell = false;
  56874. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56875. this.translationPivot = new BABYLON.Vector2(0, 0);
  56876. /**
  56877. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  56878. */
  56879. this.beginAnimationOnStart = false;
  56880. /**
  56881. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  56882. */
  56883. this.beginAnimationFrom = 0;
  56884. /**
  56885. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  56886. */
  56887. this.beginAnimationTo = 60;
  56888. /**
  56889. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  56890. */
  56891. this.beginAnimationLoop = false;
  56892. /**
  56893. * You can use gravity if you want to give an orientation to your particles.
  56894. */
  56895. this.gravity = BABYLON.Vector3.Zero();
  56896. this._colorGradients = null;
  56897. this._sizeGradients = null;
  56898. this._lifeTimeGradients = null;
  56899. this._angularSpeedGradients = null;
  56900. this._velocityGradients = null;
  56901. this._limitVelocityGradients = null;
  56902. this._dragGradients = null;
  56903. this._emitRateGradients = null;
  56904. this._startSizeGradients = null;
  56905. this._rampGradients = null;
  56906. this._colorRemapGradients = null;
  56907. this._alphaRemapGradients = null;
  56908. /**
  56909. * Defines the delay in milliseconds before starting the system (0 by default)
  56910. */
  56911. this.startDelay = 0;
  56912. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56913. this.limitVelocityDamping = 0.4;
  56914. /**
  56915. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56916. */
  56917. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56918. /**
  56919. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56920. */
  56921. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56922. /**
  56923. * Color the particle will have at the end of its lifetime
  56924. */
  56925. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56926. /**
  56927. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56928. */
  56929. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56930. /** @hidden */
  56931. this._isSubEmitter = false;
  56932. /**
  56933. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56934. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  56935. */
  56936. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  56937. this._isBillboardBased = true;
  56938. /**
  56939. * Local cache of defines for image processing.
  56940. */
  56941. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56942. this.id = name;
  56943. this.name = name;
  56944. }
  56945. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56946. /**
  56947. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56948. */
  56949. get: function () {
  56950. return this._isAnimationSheetEnabled;
  56951. },
  56952. set: function (value) {
  56953. if (this._isAnimationSheetEnabled == value) {
  56954. return;
  56955. }
  56956. this._isAnimationSheetEnabled = value;
  56957. this._reset();
  56958. },
  56959. enumerable: true,
  56960. configurable: true
  56961. });
  56962. /**
  56963. * Get hosting scene
  56964. * @returns the scene
  56965. */
  56966. BaseParticleSystem.prototype.getScene = function () {
  56967. return this._scene;
  56968. };
  56969. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56970. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56971. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56972. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56973. };
  56974. /**
  56975. * Gets the current list of drag gradients.
  56976. * You must use addDragGradient and removeDragGradient to udpate this list
  56977. * @returns the list of drag gradients
  56978. */
  56979. BaseParticleSystem.prototype.getDragGradients = function () {
  56980. return this._dragGradients;
  56981. };
  56982. /**
  56983. * Gets the current list of limit velocity gradients.
  56984. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56985. * @returns the list of limit velocity gradients
  56986. */
  56987. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56988. return this._limitVelocityGradients;
  56989. };
  56990. /**
  56991. * Gets the current list of color gradients.
  56992. * You must use addColorGradient and removeColorGradient to udpate this list
  56993. * @returns the list of color gradients
  56994. */
  56995. BaseParticleSystem.prototype.getColorGradients = function () {
  56996. return this._colorGradients;
  56997. };
  56998. /**
  56999. * Gets the current list of size gradients.
  57000. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57001. * @returns the list of size gradients
  57002. */
  57003. BaseParticleSystem.prototype.getSizeGradients = function () {
  57004. return this._sizeGradients;
  57005. };
  57006. /**
  57007. * Gets the current list of color remap gradients.
  57008. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57009. * @returns the list of color remap gradients
  57010. */
  57011. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57012. return this._colorRemapGradients;
  57013. };
  57014. /**
  57015. * Gets the current list of alpha remap gradients.
  57016. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  57017. * @returns the list of alpha remap gradients
  57018. */
  57019. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  57020. return this._alphaRemapGradients;
  57021. };
  57022. /**
  57023. * Gets the current list of life time gradients.
  57024. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  57025. * @returns the list of life time gradients
  57026. */
  57027. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  57028. return this._lifeTimeGradients;
  57029. };
  57030. /**
  57031. * Gets the current list of angular speed gradients.
  57032. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57033. * @returns the list of angular speed gradients
  57034. */
  57035. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  57036. return this._angularSpeedGradients;
  57037. };
  57038. /**
  57039. * Gets the current list of velocity gradients.
  57040. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57041. * @returns the list of velocity gradients
  57042. */
  57043. BaseParticleSystem.prototype.getVelocityGradients = function () {
  57044. return this._velocityGradients;
  57045. };
  57046. /**
  57047. * Gets the current list of start size gradients.
  57048. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  57049. * @returns the list of start size gradients
  57050. */
  57051. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  57052. return this._startSizeGradients;
  57053. };
  57054. /**
  57055. * Gets the current list of emit rate gradients.
  57056. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  57057. * @returns the list of emit rate gradients
  57058. */
  57059. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  57060. return this._emitRateGradients;
  57061. };
  57062. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  57063. /**
  57064. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57065. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57066. */
  57067. get: function () {
  57068. if (this.particleEmitterType.direction1) {
  57069. return this.particleEmitterType.direction1;
  57070. }
  57071. return BABYLON.Vector3.Zero();
  57072. },
  57073. set: function (value) {
  57074. if (this.particleEmitterType.direction1) {
  57075. this.particleEmitterType.direction1 = value;
  57076. }
  57077. },
  57078. enumerable: true,
  57079. configurable: true
  57080. });
  57081. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  57082. /**
  57083. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57084. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57085. */
  57086. get: function () {
  57087. if (this.particleEmitterType.direction2) {
  57088. return this.particleEmitterType.direction2;
  57089. }
  57090. return BABYLON.Vector3.Zero();
  57091. },
  57092. set: function (value) {
  57093. if (this.particleEmitterType.direction2) {
  57094. this.particleEmitterType.direction2 = value;
  57095. }
  57096. },
  57097. enumerable: true,
  57098. configurable: true
  57099. });
  57100. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  57101. /**
  57102. * 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.
  57103. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57104. */
  57105. get: function () {
  57106. if (this.particleEmitterType.minEmitBox) {
  57107. return this.particleEmitterType.minEmitBox;
  57108. }
  57109. return BABYLON.Vector3.Zero();
  57110. },
  57111. set: function (value) {
  57112. if (this.particleEmitterType.minEmitBox) {
  57113. this.particleEmitterType.minEmitBox = value;
  57114. }
  57115. },
  57116. enumerable: true,
  57117. configurable: true
  57118. });
  57119. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  57120. /**
  57121. * 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.
  57122. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57123. */
  57124. get: function () {
  57125. if (this.particleEmitterType.maxEmitBox) {
  57126. return this.particleEmitterType.maxEmitBox;
  57127. }
  57128. return BABYLON.Vector3.Zero();
  57129. },
  57130. set: function (value) {
  57131. if (this.particleEmitterType.maxEmitBox) {
  57132. this.particleEmitterType.maxEmitBox = value;
  57133. }
  57134. },
  57135. enumerable: true,
  57136. configurable: true
  57137. });
  57138. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  57139. /**
  57140. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57141. */
  57142. get: function () {
  57143. return this._isBillboardBased;
  57144. },
  57145. set: function (value) {
  57146. if (this._isBillboardBased === value) {
  57147. return;
  57148. }
  57149. this._isBillboardBased = value;
  57150. this._reset();
  57151. },
  57152. enumerable: true,
  57153. configurable: true
  57154. });
  57155. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  57156. /**
  57157. * Gets the image processing configuration used either in this material.
  57158. */
  57159. get: function () {
  57160. return this._imageProcessingConfiguration;
  57161. },
  57162. /**
  57163. * Sets the Default image processing configuration used either in the this material.
  57164. *
  57165. * If sets to null, the scene one is in use.
  57166. */
  57167. set: function (value) {
  57168. this._attachImageProcessingConfiguration(value);
  57169. },
  57170. enumerable: true,
  57171. configurable: true
  57172. });
  57173. /**
  57174. * Attaches a new image processing configuration to the Standard Material.
  57175. * @param configuration
  57176. */
  57177. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  57178. if (configuration === this._imageProcessingConfiguration) {
  57179. return;
  57180. }
  57181. // Pick the scene configuration if needed.
  57182. if (!configuration) {
  57183. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  57184. }
  57185. else {
  57186. this._imageProcessingConfiguration = configuration;
  57187. }
  57188. };
  57189. /** @hidden */
  57190. BaseParticleSystem.prototype._reset = function () {
  57191. };
  57192. /** @hidden */
  57193. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  57194. if (!gradients) {
  57195. return this;
  57196. }
  57197. var index = 0;
  57198. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57199. var valueGradient = gradients_1[_i];
  57200. if (valueGradient.gradient === gradient) {
  57201. gradients.splice(index, 1);
  57202. break;
  57203. }
  57204. index++;
  57205. }
  57206. if (texture) {
  57207. texture.dispose();
  57208. }
  57209. return this;
  57210. };
  57211. /**
  57212. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  57213. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57214. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57215. * @returns the emitter
  57216. */
  57217. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  57218. var particleEmitter = new BABYLON.PointParticleEmitter();
  57219. particleEmitter.direction1 = direction1;
  57220. particleEmitter.direction2 = direction2;
  57221. this.particleEmitterType = particleEmitter;
  57222. return particleEmitter;
  57223. };
  57224. /**
  57225. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  57226. * @param radius The radius of the hemisphere to emit from
  57227. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57228. * @returns the emitter
  57229. */
  57230. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  57231. if (radius === void 0) { radius = 1; }
  57232. if (radiusRange === void 0) { radiusRange = 1; }
  57233. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  57234. this.particleEmitterType = particleEmitter;
  57235. return particleEmitter;
  57236. };
  57237. /**
  57238. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  57239. * @param radius The radius of the sphere to emit from
  57240. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  57241. * @returns the emitter
  57242. */
  57243. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  57244. if (radius === void 0) { radius = 1; }
  57245. if (radiusRange === void 0) { radiusRange = 1; }
  57246. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  57247. this.particleEmitterType = particleEmitter;
  57248. return particleEmitter;
  57249. };
  57250. /**
  57251. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  57252. * @param radius The radius of the sphere to emit from
  57253. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  57254. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  57255. * @returns the emitter
  57256. */
  57257. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  57258. if (radius === void 0) { radius = 1; }
  57259. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57260. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57261. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57262. this.particleEmitterType = particleEmitter;
  57263. return particleEmitter;
  57264. };
  57265. /**
  57266. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57267. * @param radius The radius of the emission cylinder
  57268. * @param height The height of the emission cylinder
  57269. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57270. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57271. * @returns the emitter
  57272. */
  57273. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57274. if (radius === void 0) { radius = 1; }
  57275. if (height === void 0) { height = 1; }
  57276. if (radiusRange === void 0) { radiusRange = 1; }
  57277. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57278. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57279. this.particleEmitterType = particleEmitter;
  57280. return particleEmitter;
  57281. };
  57282. /**
  57283. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57284. * @param radius The radius of the cylinder to emit from
  57285. * @param height The height of the emission cylinder
  57286. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57287. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57288. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57289. * @returns the emitter
  57290. */
  57291. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57292. if (radius === void 0) { radius = 1; }
  57293. if (height === void 0) { height = 1; }
  57294. if (radiusRange === void 0) { radiusRange = 1; }
  57295. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57296. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57297. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57298. this.particleEmitterType = particleEmitter;
  57299. return particleEmitter;
  57300. };
  57301. /**
  57302. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57303. * @param radius The radius of the cone to emit from
  57304. * @param angle The base angle of the cone
  57305. * @returns the emitter
  57306. */
  57307. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57308. if (radius === void 0) { radius = 1; }
  57309. if (angle === void 0) { angle = Math.PI / 4; }
  57310. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57311. this.particleEmitterType = particleEmitter;
  57312. return particleEmitter;
  57313. };
  57314. /**
  57315. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57316. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57317. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57318. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57319. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57320. * @returns the emitter
  57321. */
  57322. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57323. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57324. this.particleEmitterType = particleEmitter;
  57325. this.direction1 = direction1;
  57326. this.direction2 = direction2;
  57327. this.minEmitBox = minEmitBox;
  57328. this.maxEmitBox = maxEmitBox;
  57329. return particleEmitter;
  57330. };
  57331. /**
  57332. * Source color is added to the destination color without alpha affecting the result
  57333. */
  57334. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57335. /**
  57336. * Blend current color and particle color using particle’s alpha
  57337. */
  57338. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57339. /**
  57340. * Add current color and particle color multiplied by particle’s alpha
  57341. */
  57342. BaseParticleSystem.BLENDMODE_ADD = 2;
  57343. /**
  57344. * Multiply current color with particle color
  57345. */
  57346. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57347. /**
  57348. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57349. */
  57350. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57351. return BaseParticleSystem;
  57352. }());
  57353. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57354. })(BABYLON || (BABYLON = {}));
  57355. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57356. var BABYLON;
  57357. (function (BABYLON) {
  57358. /**
  57359. * This represents a particle system in Babylon.
  57360. * 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.
  57361. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57362. * @example https://doc.babylonjs.com/babylon101/particles
  57363. */
  57364. var ParticleSystem = /** @class */ (function (_super) {
  57365. __extends(ParticleSystem, _super);
  57366. /**
  57367. * Instantiates a particle system.
  57368. * 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.
  57369. * @param name The name of the particle system
  57370. * @param capacity The max number of particles alive at the same time
  57371. * @param scene The scene the particle system belongs to
  57372. * @param customEffect a custom effect used to change the way particles are rendered by default
  57373. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57374. * @param epsilon Offset used to render the particles
  57375. */
  57376. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57377. if (customEffect === void 0) { customEffect = null; }
  57378. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57379. if (epsilon === void 0) { epsilon = 0.01; }
  57380. var _this = _super.call(this, name) || this;
  57381. /**
  57382. * @hidden
  57383. */
  57384. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57385. /**
  57386. * An event triggered when the system is disposed
  57387. */
  57388. _this.onDisposeObservable = new BABYLON.Observable();
  57389. _this._particles = new Array();
  57390. _this._stockParticles = new Array();
  57391. _this._newPartsExcess = 0;
  57392. _this._vertexBuffers = {};
  57393. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57394. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57395. _this._scaledDirection = BABYLON.Vector3.Zero();
  57396. _this._scaledGravity = BABYLON.Vector3.Zero();
  57397. _this._currentRenderId = -1;
  57398. _this._useInstancing = false;
  57399. _this._started = false;
  57400. _this._stopped = false;
  57401. _this._actualFrame = 0;
  57402. /** @hidden */
  57403. _this._currentEmitRate1 = 0;
  57404. /** @hidden */
  57405. _this._currentEmitRate2 = 0;
  57406. /** @hidden */
  57407. _this._currentStartSize1 = 0;
  57408. /** @hidden */
  57409. _this._currentStartSize2 = 0;
  57410. _this._rawTextureWidth = 256;
  57411. _this._useRampGradients = false;
  57412. /**
  57413. * @hidden
  57414. * If the particle systems emitter should be disposed when the particle system is disposed
  57415. */
  57416. _this._disposeEmitterOnDispose = false;
  57417. // start of sub system methods
  57418. /**
  57419. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57420. * Its lifetime will start back at 0.
  57421. */
  57422. _this.recycleParticle = function (particle) {
  57423. // move particle from activeParticle list to stock particles
  57424. var lastParticle = _this._particles.pop();
  57425. if (lastParticle !== particle) {
  57426. lastParticle.copyTo(particle);
  57427. }
  57428. _this._stockParticles.push(lastParticle);
  57429. };
  57430. _this._createParticle = function () {
  57431. var particle;
  57432. if (_this._stockParticles.length !== 0) {
  57433. particle = _this._stockParticles.pop();
  57434. particle._reset();
  57435. }
  57436. else {
  57437. particle = new BABYLON.Particle(_this);
  57438. }
  57439. // Attach emitters
  57440. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57441. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57442. particle._attachedSubEmitters = [];
  57443. subEmitters.forEach(function (subEmitter) {
  57444. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57445. var newEmitter = subEmitter.clone();
  57446. particle._attachedSubEmitters.push(newEmitter);
  57447. newEmitter.particleSystem.start();
  57448. }
  57449. });
  57450. }
  57451. return particle;
  57452. };
  57453. _this._emitFromParticle = function (particle) {
  57454. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57455. return;
  57456. }
  57457. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57458. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57459. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57460. var subSystem = subEmitter.clone();
  57461. particle._inheritParticleInfoToSubEmitter(subSystem);
  57462. subSystem.particleSystem._rootParticleSystem = _this;
  57463. _this.activeSubSystems.push(subSystem.particleSystem);
  57464. subSystem.particleSystem.start();
  57465. }
  57466. });
  57467. };
  57468. _this._capacity = capacity;
  57469. _this._epsilon = epsilon;
  57470. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57471. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57472. // Setup the default processing configuration to the scene.
  57473. _this._attachImageProcessingConfiguration(null);
  57474. _this._customEffect = customEffect;
  57475. _this._scene.particleSystems.push(_this);
  57476. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57477. _this._createIndexBuffer();
  57478. _this._createVertexBuffers();
  57479. // Default emitter type
  57480. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57481. // Update
  57482. _this.updateFunction = function (particles) {
  57483. var noiseTextureSize = null;
  57484. var noiseTextureData = null;
  57485. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57486. noiseTextureSize = _this.noiseTexture.getSize();
  57487. noiseTextureData = (_this.noiseTexture.getContent());
  57488. }
  57489. var _loop_1 = function () {
  57490. particle = particles[index];
  57491. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57492. var previousAge = particle.age;
  57493. particle.age += scaledUpdateSpeed;
  57494. // Evaluate step to death
  57495. if (particle.age > particle.lifeTime) {
  57496. var diff = particle.age - previousAge;
  57497. var oldDiff = particle.lifeTime - previousAge;
  57498. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57499. particle.age = particle.lifeTime;
  57500. }
  57501. var ratio = particle.age / particle.lifeTime;
  57502. // Color
  57503. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57504. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57505. if (currentGradient !== particle._currentColorGradient) {
  57506. particle._currentColor1.copyFrom(particle._currentColor2);
  57507. nextGradient.getColorToRef(particle._currentColor2);
  57508. particle._currentColorGradient = currentGradient;
  57509. }
  57510. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57511. });
  57512. }
  57513. else {
  57514. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57515. particle.color.addInPlace(_this._scaledColorStep);
  57516. if (particle.color.a < 0) {
  57517. particle.color.a = 0;
  57518. }
  57519. }
  57520. // Angular speed
  57521. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57522. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57523. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57524. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57525. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57526. particle._currentAngularSpeedGradient = currentGradient;
  57527. }
  57528. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57529. });
  57530. }
  57531. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57532. // Direction
  57533. var directionScale = scaledUpdateSpeed;
  57534. /// Velocity
  57535. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57536. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57537. if (currentGradient !== particle._currentVelocityGradient) {
  57538. particle._currentVelocity1 = particle._currentVelocity2;
  57539. particle._currentVelocity2 = nextGradient.getFactor();
  57540. particle._currentVelocityGradient = currentGradient;
  57541. }
  57542. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57543. });
  57544. }
  57545. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57546. /// Limit velocity
  57547. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57548. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57549. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57550. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57551. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57552. particle._currentLimitVelocityGradient = currentGradient;
  57553. }
  57554. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57555. var currentVelocity = particle.direction.length();
  57556. if (currentVelocity > limitVelocity) {
  57557. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57558. }
  57559. });
  57560. }
  57561. /// Drag
  57562. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57563. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57564. if (currentGradient !== particle._currentDragGradient) {
  57565. particle._currentDrag1 = particle._currentDrag2;
  57566. particle._currentDrag2 = nextGradient.getFactor();
  57567. particle._currentDragGradient = currentGradient;
  57568. }
  57569. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57570. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57571. });
  57572. }
  57573. particle.position.addInPlace(_this._scaledDirection);
  57574. // Noise
  57575. if (noiseTextureData && noiseTextureSize) {
  57576. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57577. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57578. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57579. var force = BABYLON.Tmp.Vector3[0];
  57580. var scaledForce = BABYLON.Tmp.Vector3[1];
  57581. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57582. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57583. particle.direction.addInPlace(scaledForce);
  57584. }
  57585. // Gravity
  57586. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57587. particle.direction.addInPlace(_this._scaledGravity);
  57588. // Size
  57589. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57590. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57591. if (currentGradient !== particle._currentSizeGradient) {
  57592. particle._currentSize1 = particle._currentSize2;
  57593. particle._currentSize2 = nextGradient.getFactor();
  57594. particle._currentSizeGradient = currentGradient;
  57595. }
  57596. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57597. });
  57598. }
  57599. // Remap data
  57600. if (_this._useRampGradients) {
  57601. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57602. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57603. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57604. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57605. particle.remapData.x = min;
  57606. particle.remapData.y = max - min;
  57607. });
  57608. }
  57609. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57610. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57611. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57612. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57613. particle.remapData.z = min;
  57614. particle.remapData.w = max - min;
  57615. });
  57616. }
  57617. }
  57618. if (_this._isAnimationSheetEnabled) {
  57619. particle.updateCellIndex();
  57620. }
  57621. // Update the position of the attached sub-emitters to match their attached particle
  57622. particle._inheritParticleInfoToSubEmitters();
  57623. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57624. _this._emitFromParticle(particle);
  57625. if (particle._attachedSubEmitters) {
  57626. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57627. subEmitter.particleSystem.disposeOnStop = true;
  57628. subEmitter.particleSystem.stop();
  57629. });
  57630. particle._attachedSubEmitters = null;
  57631. }
  57632. _this.recycleParticle(particle);
  57633. index--;
  57634. return "continue";
  57635. }
  57636. };
  57637. var particle;
  57638. for (var index = 0; index < particles.length; index++) {
  57639. _loop_1();
  57640. }
  57641. };
  57642. return _this;
  57643. }
  57644. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57645. /**
  57646. * Sets a callback that will be triggered when the system is disposed
  57647. */
  57648. set: function (callback) {
  57649. if (this._onDisposeObserver) {
  57650. this.onDisposeObservable.remove(this._onDisposeObserver);
  57651. }
  57652. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57653. },
  57654. enumerable: true,
  57655. configurable: true
  57656. });
  57657. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57658. /** Gets or sets a boolean indicating that ramp gradients must be used
  57659. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57660. */
  57661. get: function () {
  57662. return this._useRampGradients;
  57663. },
  57664. set: function (value) {
  57665. if (this._useRampGradients === value) {
  57666. return;
  57667. }
  57668. this._useRampGradients = value;
  57669. this._resetEffect();
  57670. },
  57671. enumerable: true,
  57672. configurable: true
  57673. });
  57674. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57675. //end of Sub-emitter
  57676. /**
  57677. * Gets the current list of active particles
  57678. */
  57679. get: function () {
  57680. return this._particles;
  57681. },
  57682. enumerable: true,
  57683. configurable: true
  57684. });
  57685. /**
  57686. * Returns the string "ParticleSystem"
  57687. * @returns a string containing the class name
  57688. */
  57689. ParticleSystem.prototype.getClassName = function () {
  57690. return "ParticleSystem";
  57691. };
  57692. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57693. var newGradient = new BABYLON.FactorGradient();
  57694. newGradient.gradient = gradient;
  57695. newGradient.factor1 = factor;
  57696. newGradient.factor2 = factor2;
  57697. factorGradients.push(newGradient);
  57698. factorGradients.sort(function (a, b) {
  57699. if (a.gradient < b.gradient) {
  57700. return -1;
  57701. }
  57702. else if (a.gradient > b.gradient) {
  57703. return 1;
  57704. }
  57705. return 0;
  57706. });
  57707. };
  57708. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57709. if (!factorGradients) {
  57710. return;
  57711. }
  57712. var index = 0;
  57713. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57714. var factorGradient = factorGradients_1[_i];
  57715. if (factorGradient.gradient === gradient) {
  57716. factorGradients.splice(index, 1);
  57717. break;
  57718. }
  57719. index++;
  57720. }
  57721. };
  57722. /**
  57723. * Adds a new life time gradient
  57724. * @param gradient defines the gradient to use (between 0 and 1)
  57725. * @param factor defines the life time factor to affect to the specified gradient
  57726. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57727. * @returns the current particle system
  57728. */
  57729. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57730. if (!this._lifeTimeGradients) {
  57731. this._lifeTimeGradients = [];
  57732. }
  57733. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57734. return this;
  57735. };
  57736. /**
  57737. * Remove a specific life time gradient
  57738. * @param gradient defines the gradient to remove
  57739. * @returns the current particle system
  57740. */
  57741. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57742. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57743. return this;
  57744. };
  57745. /**
  57746. * Adds a new size gradient
  57747. * @param gradient defines the gradient to use (between 0 and 1)
  57748. * @param factor defines the size factor to affect to the specified gradient
  57749. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57750. * @returns the current particle system
  57751. */
  57752. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57753. if (!this._sizeGradients) {
  57754. this._sizeGradients = [];
  57755. }
  57756. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57757. return this;
  57758. };
  57759. /**
  57760. * Remove a specific size gradient
  57761. * @param gradient defines the gradient to remove
  57762. * @returns the current particle system
  57763. */
  57764. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57765. this._removeFactorGradient(this._sizeGradients, gradient);
  57766. return this;
  57767. };
  57768. /**
  57769. * Adds a new color remap gradient
  57770. * @param gradient defines the gradient to use (between 0 and 1)
  57771. * @param min defines the color remap minimal range
  57772. * @param max defines the color remap maximal range
  57773. * @returns the current particle system
  57774. */
  57775. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57776. if (!this._colorRemapGradients) {
  57777. this._colorRemapGradients = [];
  57778. }
  57779. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57780. return this;
  57781. };
  57782. /**
  57783. * Remove a specific color remap gradient
  57784. * @param gradient defines the gradient to remove
  57785. * @returns the current particle system
  57786. */
  57787. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57788. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57789. return this;
  57790. };
  57791. /**
  57792. * Adds a new alpha remap gradient
  57793. * @param gradient defines the gradient to use (between 0 and 1)
  57794. * @param min defines the alpha remap minimal range
  57795. * @param max defines the alpha remap maximal range
  57796. * @returns the current particle system
  57797. */
  57798. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57799. if (!this._alphaRemapGradients) {
  57800. this._alphaRemapGradients = [];
  57801. }
  57802. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57803. return this;
  57804. };
  57805. /**
  57806. * Remove a specific alpha remap gradient
  57807. * @param gradient defines the gradient to remove
  57808. * @returns the current particle system
  57809. */
  57810. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57811. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57812. return this;
  57813. };
  57814. /**
  57815. * Adds a new angular speed gradient
  57816. * @param gradient defines the gradient to use (between 0 and 1)
  57817. * @param factor defines the angular speed to affect to the specified gradient
  57818. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57819. * @returns the current particle system
  57820. */
  57821. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57822. if (!this._angularSpeedGradients) {
  57823. this._angularSpeedGradients = [];
  57824. }
  57825. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57826. return this;
  57827. };
  57828. /**
  57829. * Remove a specific angular speed gradient
  57830. * @param gradient defines the gradient to remove
  57831. * @returns the current particle system
  57832. */
  57833. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57834. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57835. return this;
  57836. };
  57837. /**
  57838. * Adds a new velocity gradient
  57839. * @param gradient defines the gradient to use (between 0 and 1)
  57840. * @param factor defines the velocity to affect to the specified gradient
  57841. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57842. * @returns the current particle system
  57843. */
  57844. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57845. if (!this._velocityGradients) {
  57846. this._velocityGradients = [];
  57847. }
  57848. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57849. return this;
  57850. };
  57851. /**
  57852. * Remove a specific velocity gradient
  57853. * @param gradient defines the gradient to remove
  57854. * @returns the current particle system
  57855. */
  57856. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57857. this._removeFactorGradient(this._velocityGradients, gradient);
  57858. return this;
  57859. };
  57860. /**
  57861. * Adds a new limit velocity gradient
  57862. * @param gradient defines the gradient to use (between 0 and 1)
  57863. * @param factor defines the limit velocity value to affect to the specified gradient
  57864. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57865. * @returns the current particle system
  57866. */
  57867. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57868. if (!this._limitVelocityGradients) {
  57869. this._limitVelocityGradients = [];
  57870. }
  57871. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57872. return this;
  57873. };
  57874. /**
  57875. * Remove a specific limit velocity gradient
  57876. * @param gradient defines the gradient to remove
  57877. * @returns the current particle system
  57878. */
  57879. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57880. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57881. return this;
  57882. };
  57883. /**
  57884. * Adds a new drag gradient
  57885. * @param gradient defines the gradient to use (between 0 and 1)
  57886. * @param factor defines the drag value to affect to the specified gradient
  57887. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57888. * @returns the current particle system
  57889. */
  57890. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57891. if (!this._dragGradients) {
  57892. this._dragGradients = [];
  57893. }
  57894. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57895. return this;
  57896. };
  57897. /**
  57898. * Remove a specific drag gradient
  57899. * @param gradient defines the gradient to remove
  57900. * @returns the current particle system
  57901. */
  57902. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57903. this._removeFactorGradient(this._dragGradients, gradient);
  57904. return this;
  57905. };
  57906. /**
  57907. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57908. * @param gradient defines the gradient to use (between 0 and 1)
  57909. * @param factor defines the emit rate value to affect to the specified gradient
  57910. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57911. * @returns the current particle system
  57912. */
  57913. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57914. if (!this._emitRateGradients) {
  57915. this._emitRateGradients = [];
  57916. }
  57917. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57918. if (!this._currentEmitRateGradient) {
  57919. this._currentEmitRateGradient = this._emitRateGradients[0];
  57920. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57921. this._currentEmitRate2 = this._currentEmitRate1;
  57922. }
  57923. if (this._emitRateGradients.length === 2) {
  57924. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57925. }
  57926. return this;
  57927. };
  57928. /**
  57929. * Remove a specific emit rate gradient
  57930. * @param gradient defines the gradient to remove
  57931. * @returns the current particle system
  57932. */
  57933. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57934. this._removeFactorGradient(this._emitRateGradients, gradient);
  57935. return this;
  57936. };
  57937. /**
  57938. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57939. * @param gradient defines the gradient to use (between 0 and 1)
  57940. * @param factor defines the start size value to affect to the specified gradient
  57941. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57942. * @returns the current particle system
  57943. */
  57944. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57945. if (!this._startSizeGradients) {
  57946. this._startSizeGradients = [];
  57947. }
  57948. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57949. if (!this._currentStartSizeGradient) {
  57950. this._currentStartSizeGradient = this._startSizeGradients[0];
  57951. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57952. this._currentStartSize2 = this._currentStartSize1;
  57953. }
  57954. if (this._startSizeGradients.length === 2) {
  57955. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57956. }
  57957. return this;
  57958. };
  57959. /**
  57960. * Remove a specific start size gradient
  57961. * @param gradient defines the gradient to remove
  57962. * @returns the current particle system
  57963. */
  57964. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57965. this._removeFactorGradient(this._emitRateGradients, gradient);
  57966. return this;
  57967. };
  57968. ParticleSystem.prototype._createRampGradientTexture = function () {
  57969. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57970. return;
  57971. }
  57972. var data = new Uint8Array(this._rawTextureWidth * 4);
  57973. var tmpColor = BABYLON.Tmp.Color3[0];
  57974. for (var x = 0; x < this._rawTextureWidth; x++) {
  57975. var ratio = x / this._rawTextureWidth;
  57976. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57977. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57978. data[x * 4] = tmpColor.r * 255;
  57979. data[x * 4 + 1] = tmpColor.g * 255;
  57980. data[x * 4 + 2] = tmpColor.b * 255;
  57981. data[x * 4 + 3] = 255;
  57982. });
  57983. }
  57984. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57985. };
  57986. /**
  57987. * Gets the current list of ramp gradients.
  57988. * You must use addRampGradient and removeRampGradient to udpate this list
  57989. * @returns the list of ramp gradients
  57990. */
  57991. ParticleSystem.prototype.getRampGradients = function () {
  57992. return this._rampGradients;
  57993. };
  57994. /**
  57995. * Adds a new ramp gradient used to remap particle colors
  57996. * @param gradient defines the gradient to use (between 0 and 1)
  57997. * @param color defines the color to affect to the specified gradient
  57998. * @returns the current particle system
  57999. */
  58000. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58001. if (!this._rampGradients) {
  58002. this._rampGradients = [];
  58003. }
  58004. var rampGradient = new BABYLON.Color3Gradient();
  58005. rampGradient.gradient = gradient;
  58006. rampGradient.color = color;
  58007. this._rampGradients.push(rampGradient);
  58008. this._rampGradients.sort(function (a, b) {
  58009. if (a.gradient < b.gradient) {
  58010. return -1;
  58011. }
  58012. else if (a.gradient > b.gradient) {
  58013. return 1;
  58014. }
  58015. return 0;
  58016. });
  58017. if (this._rampGradientsTexture) {
  58018. this._rampGradientsTexture.dispose();
  58019. this._rampGradientsTexture = null;
  58020. }
  58021. this._createRampGradientTexture();
  58022. return this;
  58023. };
  58024. /**
  58025. * Remove a specific ramp gradient
  58026. * @param gradient defines the gradient to remove
  58027. * @returns the current particle system
  58028. */
  58029. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  58030. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  58031. this._rampGradientsTexture = null;
  58032. if (this._rampGradients && this._rampGradients.length > 0) {
  58033. this._createRampGradientTexture();
  58034. }
  58035. return this;
  58036. };
  58037. /**
  58038. * Adds a new color gradient
  58039. * @param gradient defines the gradient to use (between 0 and 1)
  58040. * @param color1 defines the color to affect to the specified gradient
  58041. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  58042. */
  58043. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  58044. if (!this._colorGradients) {
  58045. this._colorGradients = [];
  58046. }
  58047. var colorGradient = new BABYLON.ColorGradient();
  58048. colorGradient.gradient = gradient;
  58049. colorGradient.color1 = color1;
  58050. colorGradient.color2 = color2;
  58051. this._colorGradients.push(colorGradient);
  58052. this._colorGradients.sort(function (a, b) {
  58053. if (a.gradient < b.gradient) {
  58054. return -1;
  58055. }
  58056. else if (a.gradient > b.gradient) {
  58057. return 1;
  58058. }
  58059. return 0;
  58060. });
  58061. return this;
  58062. };
  58063. /**
  58064. * Remove a specific color gradient
  58065. * @param gradient defines the gradient to remove
  58066. */
  58067. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  58068. if (!this._colorGradients) {
  58069. return this;
  58070. }
  58071. var index = 0;
  58072. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  58073. var colorGradient = _a[_i];
  58074. if (colorGradient.gradient === gradient) {
  58075. this._colorGradients.splice(index, 1);
  58076. break;
  58077. }
  58078. index++;
  58079. }
  58080. return this;
  58081. };
  58082. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  58083. u = Math.abs(u) * 0.5 + 0.5;
  58084. v = Math.abs(v) * 0.5 + 0.5;
  58085. var wrappedU = ((u * width) % width) | 0;
  58086. var wrappedV = ((v * height) % height) | 0;
  58087. var position = (wrappedU + wrappedV * width) * 4;
  58088. return pixels[position] / 255;
  58089. };
  58090. ParticleSystem.prototype._reset = function () {
  58091. this._resetEffect();
  58092. };
  58093. ParticleSystem.prototype._resetEffect = function () {
  58094. if (this._vertexBuffer) {
  58095. this._vertexBuffer.dispose();
  58096. this._vertexBuffer = null;
  58097. }
  58098. if (this._spriteBuffer) {
  58099. this._spriteBuffer.dispose();
  58100. this._spriteBuffer = null;
  58101. }
  58102. this._createVertexBuffers();
  58103. };
  58104. ParticleSystem.prototype._createVertexBuffers = function () {
  58105. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  58106. if (this._isAnimationSheetEnabled) {
  58107. this._vertexBufferSize += 1;
  58108. }
  58109. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58110. this._vertexBufferSize += 3;
  58111. }
  58112. if (this._useRampGradients) {
  58113. this._vertexBufferSize += 4;
  58114. }
  58115. var engine = this._scene.getEngine();
  58116. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  58117. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  58118. var dataOffset = 0;
  58119. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58120. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  58121. dataOffset += 3;
  58122. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58123. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  58124. dataOffset += 4;
  58125. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58126. this._vertexBuffers["angle"] = options;
  58127. dataOffset += 1;
  58128. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58129. this._vertexBuffers["size"] = size;
  58130. dataOffset += 2;
  58131. if (this._isAnimationSheetEnabled) {
  58132. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  58133. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  58134. dataOffset += 1;
  58135. }
  58136. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58137. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  58138. this._vertexBuffers["direction"] = directionBuffer;
  58139. dataOffset += 3;
  58140. }
  58141. if (this._useRampGradients) {
  58142. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  58143. this._vertexBuffers["remapData"] = rampDataBuffer;
  58144. dataOffset += 4;
  58145. }
  58146. var offsets;
  58147. if (this._useInstancing) {
  58148. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  58149. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  58150. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  58151. }
  58152. else {
  58153. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  58154. dataOffset += 2;
  58155. }
  58156. this._vertexBuffers["offset"] = offsets;
  58157. };
  58158. ParticleSystem.prototype._createIndexBuffer = function () {
  58159. if (this._useInstancing) {
  58160. return;
  58161. }
  58162. var indices = [];
  58163. var index = 0;
  58164. for (var count = 0; count < this._capacity; count++) {
  58165. indices.push(index);
  58166. indices.push(index + 1);
  58167. indices.push(index + 2);
  58168. indices.push(index);
  58169. indices.push(index + 2);
  58170. indices.push(index + 3);
  58171. index += 4;
  58172. }
  58173. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  58174. };
  58175. /**
  58176. * Gets the maximum number of particles active at the same time.
  58177. * @returns The max number of active particles.
  58178. */
  58179. ParticleSystem.prototype.getCapacity = function () {
  58180. return this._capacity;
  58181. };
  58182. /**
  58183. * Gets whether there are still active particles in the system.
  58184. * @returns True if it is alive, otherwise false.
  58185. */
  58186. ParticleSystem.prototype.isAlive = function () {
  58187. return this._alive;
  58188. };
  58189. /**
  58190. * Gets if the system has been started. (Note: this will still be true after stop is called)
  58191. * @returns True if it has been started, otherwise false.
  58192. */
  58193. ParticleSystem.prototype.isStarted = function () {
  58194. return this._started;
  58195. };
  58196. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  58197. var _this = this;
  58198. this._subEmitters = new Array();
  58199. if (this.subEmitters) {
  58200. this.subEmitters.forEach(function (subEmitter) {
  58201. if (subEmitter instanceof ParticleSystem) {
  58202. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  58203. }
  58204. else if (subEmitter instanceof BABYLON.SubEmitter) {
  58205. _this._subEmitters.push([subEmitter]);
  58206. }
  58207. else if (subEmitter instanceof Array) {
  58208. _this._subEmitters.push(subEmitter);
  58209. }
  58210. });
  58211. }
  58212. };
  58213. /**
  58214. * Starts the particle system and begins to emit
  58215. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  58216. */
  58217. ParticleSystem.prototype.start = function (delay) {
  58218. var _this = this;
  58219. if (delay === void 0) { delay = this.startDelay; }
  58220. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  58221. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  58222. }
  58223. if (delay) {
  58224. setTimeout(function () {
  58225. _this.start(0);
  58226. }, delay);
  58227. return;
  58228. }
  58229. // Convert the subEmitters field to the constant type field _subEmitters
  58230. this._prepareSubEmitterInternalArray();
  58231. this._started = true;
  58232. this._stopped = false;
  58233. this._actualFrame = 0;
  58234. if (this._subEmitters && this._subEmitters.length != 0) {
  58235. this.activeSubSystems = new Array();
  58236. }
  58237. if (this.preWarmCycles) {
  58238. if (this.emitter instanceof BABYLON.AbstractMesh) {
  58239. this.emitter.computeWorldMatrix(true);
  58240. }
  58241. var noiseTextureAsProcedural_1 = this.noiseTexture;
  58242. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  58243. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  58244. setTimeout(function () {
  58245. for (var index = 0; index < _this.preWarmCycles; index++) {
  58246. _this.animate(true);
  58247. noiseTextureAsProcedural_1.render();
  58248. }
  58249. });
  58250. });
  58251. }
  58252. else {
  58253. for (var index = 0; index < this.preWarmCycles; index++) {
  58254. this.animate(true);
  58255. }
  58256. }
  58257. }
  58258. // Animations
  58259. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  58260. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  58261. }
  58262. };
  58263. /**
  58264. * Stops the particle system.
  58265. * @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.
  58266. */
  58267. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58268. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58269. this._stopped = true;
  58270. if (stopSubEmitters) {
  58271. this._stopSubEmitters();
  58272. }
  58273. };
  58274. // animation sheet
  58275. /**
  58276. * Remove all active particles
  58277. */
  58278. ParticleSystem.prototype.reset = function () {
  58279. this._stockParticles = [];
  58280. this._particles = [];
  58281. };
  58282. /**
  58283. * @hidden (for internal use only)
  58284. */
  58285. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58286. var offset = index * this._vertexBufferSize;
  58287. this._vertexData[offset++] = particle.position.x;
  58288. this._vertexData[offset++] = particle.position.y;
  58289. this._vertexData[offset++] = particle.position.z;
  58290. this._vertexData[offset++] = particle.color.r;
  58291. this._vertexData[offset++] = particle.color.g;
  58292. this._vertexData[offset++] = particle.color.b;
  58293. this._vertexData[offset++] = particle.color.a;
  58294. this._vertexData[offset++] = particle.angle;
  58295. this._vertexData[offset++] = particle.scale.x * particle.size;
  58296. this._vertexData[offset++] = particle.scale.y * particle.size;
  58297. if (this._isAnimationSheetEnabled) {
  58298. this._vertexData[offset++] = particle.cellIndex;
  58299. }
  58300. if (!this._isBillboardBased) {
  58301. if (particle._initialDirection) {
  58302. this._vertexData[offset++] = particle._initialDirection.x;
  58303. this._vertexData[offset++] = particle._initialDirection.y;
  58304. this._vertexData[offset++] = particle._initialDirection.z;
  58305. }
  58306. else {
  58307. this._vertexData[offset++] = particle.direction.x;
  58308. this._vertexData[offset++] = particle.direction.y;
  58309. this._vertexData[offset++] = particle.direction.z;
  58310. }
  58311. }
  58312. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58313. this._vertexData[offset++] = particle.direction.x;
  58314. this._vertexData[offset++] = particle.direction.y;
  58315. this._vertexData[offset++] = particle.direction.z;
  58316. }
  58317. if (this._useRampGradients) {
  58318. this._vertexData[offset++] = particle.remapData.x;
  58319. this._vertexData[offset++] = particle.remapData.y;
  58320. this._vertexData[offset++] = particle.remapData.z;
  58321. this._vertexData[offset++] = particle.remapData.w;
  58322. }
  58323. if (!this._useInstancing) {
  58324. if (this._isAnimationSheetEnabled) {
  58325. if (offsetX === 0)
  58326. offsetX = this._epsilon;
  58327. else if (offsetX === 1)
  58328. offsetX = 1 - this._epsilon;
  58329. if (offsetY === 0)
  58330. offsetY = this._epsilon;
  58331. else if (offsetY === 1)
  58332. offsetY = 1 - this._epsilon;
  58333. }
  58334. this._vertexData[offset++] = offsetX;
  58335. this._vertexData[offset++] = offsetY;
  58336. }
  58337. };
  58338. ParticleSystem.prototype._stopSubEmitters = function () {
  58339. if (!this.activeSubSystems) {
  58340. return;
  58341. }
  58342. this.activeSubSystems.forEach(function (subSystem) {
  58343. subSystem.stop(true);
  58344. });
  58345. this.activeSubSystems = new Array();
  58346. };
  58347. ParticleSystem.prototype._removeFromRoot = function () {
  58348. if (!this._rootParticleSystem) {
  58349. return;
  58350. }
  58351. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58352. if (index !== -1) {
  58353. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58354. }
  58355. this._rootParticleSystem = null;
  58356. };
  58357. // End of sub system methods
  58358. ParticleSystem.prototype._update = function (newParticles) {
  58359. var _this = this;
  58360. // Update current
  58361. this._alive = this._particles.length > 0;
  58362. if (this.emitter.position) {
  58363. var emitterMesh = this.emitter;
  58364. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58365. }
  58366. else {
  58367. var emitterPosition = this.emitter;
  58368. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58369. }
  58370. this.updateFunction(this._particles);
  58371. // Add new ones
  58372. var particle;
  58373. var _loop_2 = function () {
  58374. if (this_1._particles.length === this_1._capacity) {
  58375. return "break";
  58376. }
  58377. particle = this_1._createParticle();
  58378. this_1._particles.push(particle);
  58379. // Emitter
  58380. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58381. if (this_1.startPositionFunction) {
  58382. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58383. }
  58384. else {
  58385. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58386. }
  58387. if (this_1.startDirectionFunction) {
  58388. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58389. }
  58390. else {
  58391. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58392. }
  58393. if (emitPower === 0) {
  58394. if (!particle._initialDirection) {
  58395. particle._initialDirection = particle.direction.clone();
  58396. }
  58397. else {
  58398. particle._initialDirection.copyFrom(particle.direction);
  58399. }
  58400. }
  58401. else {
  58402. particle._initialDirection = null;
  58403. }
  58404. particle.direction.scaleInPlace(emitPower);
  58405. // Life time
  58406. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58407. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58408. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58409. var factorGradient1 = currentGradient;
  58410. var factorGradient2 = nextGradient;
  58411. var lifeTime1 = factorGradient1.getFactor();
  58412. var lifeTime2 = factorGradient2.getFactor();
  58413. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58414. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58415. });
  58416. }
  58417. else {
  58418. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58419. }
  58420. // Size
  58421. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58422. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58423. }
  58424. else {
  58425. particle._currentSizeGradient = this_1._sizeGradients[0];
  58426. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58427. particle.size = particle._currentSize1;
  58428. if (this_1._sizeGradients.length > 1) {
  58429. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58430. }
  58431. else {
  58432. particle._currentSize2 = particle._currentSize1;
  58433. }
  58434. }
  58435. // Size and scale
  58436. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58437. // Adjust scale by start size
  58438. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58439. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58440. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58441. if (currentGradient !== _this._currentStartSizeGradient) {
  58442. _this._currentStartSize1 = _this._currentStartSize2;
  58443. _this._currentStartSize2 = nextGradient.getFactor();
  58444. _this._currentStartSizeGradient = currentGradient;
  58445. }
  58446. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58447. particle.scale.scaleInPlace(value);
  58448. });
  58449. }
  58450. // Angle
  58451. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58452. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58453. }
  58454. else {
  58455. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58456. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58457. particle._currentAngularSpeed1 = particle.angularSpeed;
  58458. if (this_1._angularSpeedGradients.length > 1) {
  58459. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58460. }
  58461. else {
  58462. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58463. }
  58464. }
  58465. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58466. // Velocity
  58467. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58468. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58469. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58470. if (this_1._velocityGradients.length > 1) {
  58471. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58472. }
  58473. else {
  58474. particle._currentVelocity2 = particle._currentVelocity1;
  58475. }
  58476. }
  58477. // Limit velocity
  58478. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58479. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58480. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58481. if (this_1._limitVelocityGradients.length > 1) {
  58482. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58483. }
  58484. else {
  58485. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58486. }
  58487. }
  58488. // Drag
  58489. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58490. particle._currentDragGradient = this_1._dragGradients[0];
  58491. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58492. if (this_1._dragGradients.length > 1) {
  58493. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58494. }
  58495. else {
  58496. particle._currentDrag2 = particle._currentDrag1;
  58497. }
  58498. }
  58499. // Color
  58500. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58501. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58502. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58503. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58504. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58505. }
  58506. else {
  58507. particle._currentColorGradient = this_1._colorGradients[0];
  58508. particle._currentColorGradient.getColorToRef(particle.color);
  58509. particle._currentColor1.copyFrom(particle.color);
  58510. if (this_1._colorGradients.length > 1) {
  58511. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58512. }
  58513. else {
  58514. particle._currentColor2.copyFrom(particle.color);
  58515. }
  58516. }
  58517. // Sheet
  58518. if (this_1._isAnimationSheetEnabled) {
  58519. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58520. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58521. }
  58522. // Inherited Velocity
  58523. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58524. // Ramp
  58525. if (this_1._useRampGradients) {
  58526. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58527. }
  58528. // Noise texture coordinates
  58529. if (this_1.noiseTexture) {
  58530. if (particle._randomNoiseCoordinates1) {
  58531. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58532. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58533. }
  58534. else {
  58535. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58536. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58537. }
  58538. }
  58539. // Update the position of the attached sub-emitters to match their attached particle
  58540. particle._inheritParticleInfoToSubEmitters();
  58541. };
  58542. var this_1 = this, step;
  58543. for (var index = 0; index < newParticles; index++) {
  58544. var state_1 = _loop_2();
  58545. if (state_1 === "break")
  58546. break;
  58547. }
  58548. };
  58549. /** @hidden */
  58550. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58551. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58552. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58553. if (useRampGradients === void 0) { useRampGradients = false; }
  58554. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58555. if (isAnimationSheetEnabled) {
  58556. attributeNamesOrOptions.push("cellIndex");
  58557. }
  58558. if (!isBillboardBased) {
  58559. attributeNamesOrOptions.push("direction");
  58560. }
  58561. if (useRampGradients) {
  58562. attributeNamesOrOptions.push("remapData");
  58563. }
  58564. return attributeNamesOrOptions;
  58565. };
  58566. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58567. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58568. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58569. if (isAnimationSheetEnabled) {
  58570. effectCreationOption.push("particlesInfos");
  58571. }
  58572. return effectCreationOption;
  58573. };
  58574. ParticleSystem.prototype._getEffect = function (blendMode) {
  58575. if (this._customEffect) {
  58576. return this._customEffect;
  58577. }
  58578. ;
  58579. var defines = [];
  58580. if (this._scene.clipPlane) {
  58581. defines.push("#define CLIPPLANE");
  58582. }
  58583. if (this._scene.clipPlane2) {
  58584. defines.push("#define CLIPPLANE2");
  58585. }
  58586. if (this._scene.clipPlane3) {
  58587. defines.push("#define CLIPPLANE3");
  58588. }
  58589. if (this._scene.clipPlane4) {
  58590. defines.push("#define CLIPPLANE4");
  58591. }
  58592. if (this._isAnimationSheetEnabled) {
  58593. defines.push("#define ANIMATESHEET");
  58594. }
  58595. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58596. defines.push("#define BLENDMULTIPLYMODE");
  58597. }
  58598. if (this._useRampGradients) {
  58599. defines.push("#define RAMPGRADIENT");
  58600. }
  58601. if (this._isBillboardBased) {
  58602. defines.push("#define BILLBOARD");
  58603. switch (this.billboardMode) {
  58604. case ParticleSystem.BILLBOARDMODE_Y:
  58605. defines.push("#define BILLBOARDY");
  58606. break;
  58607. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58608. defines.push("#define BILLBOARDSTRETCHED");
  58609. break;
  58610. case ParticleSystem.BILLBOARDMODE_ALL:
  58611. default:
  58612. break;
  58613. }
  58614. }
  58615. if (this._imageProcessingConfiguration) {
  58616. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58617. defines.push(this._imageProcessingConfigurationDefines.toString());
  58618. }
  58619. // Effect
  58620. var join = defines.join("\n");
  58621. if (this._cachedDefines !== join) {
  58622. this._cachedDefines = join;
  58623. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58624. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58625. var samplers = ["diffuseSampler", "rampSampler"];
  58626. if (BABYLON.ImageProcessingConfiguration) {
  58627. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58628. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58629. }
  58630. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58631. }
  58632. return this._effect;
  58633. };
  58634. /**
  58635. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58636. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58637. */
  58638. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58639. var _this = this;
  58640. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58641. if (!this._started)
  58642. return;
  58643. if (!preWarmOnly) {
  58644. // Check
  58645. if (!this.isReady())
  58646. return;
  58647. if (this._currentRenderId === this._scene.getRenderId()) {
  58648. return;
  58649. }
  58650. this._currentRenderId = this._scene.getRenderId();
  58651. }
  58652. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58653. // Determine the number of particles we need to create
  58654. var newParticles;
  58655. if (this.manualEmitCount > -1) {
  58656. newParticles = this.manualEmitCount;
  58657. this._newPartsExcess = 0;
  58658. this.manualEmitCount = 0;
  58659. }
  58660. else {
  58661. var rate_1 = this.emitRate;
  58662. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58663. var ratio = this._actualFrame / this.targetStopDuration;
  58664. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58665. if (currentGradient !== _this._currentEmitRateGradient) {
  58666. _this._currentEmitRate1 = _this._currentEmitRate2;
  58667. _this._currentEmitRate2 = nextGradient.getFactor();
  58668. _this._currentEmitRateGradient = currentGradient;
  58669. }
  58670. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58671. });
  58672. }
  58673. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58674. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58675. }
  58676. if (this._newPartsExcess > 1.0) {
  58677. newParticles += this._newPartsExcess >> 0;
  58678. this._newPartsExcess -= this._newPartsExcess >> 0;
  58679. }
  58680. this._alive = false;
  58681. if (!this._stopped) {
  58682. this._actualFrame += this._scaledUpdateSpeed;
  58683. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58684. this.stop();
  58685. }
  58686. else {
  58687. newParticles = 0;
  58688. }
  58689. this._update(newParticles);
  58690. // Stopped?
  58691. if (this._stopped) {
  58692. if (!this._alive) {
  58693. this._started = false;
  58694. if (this.onAnimationEnd) {
  58695. this.onAnimationEnd();
  58696. }
  58697. if (this.disposeOnStop) {
  58698. this._scene._toBeDisposed.push(this);
  58699. }
  58700. }
  58701. }
  58702. if (!preWarmOnly) {
  58703. // Update VBO
  58704. var offset = 0;
  58705. for (var index = 0; index < this._particles.length; index++) {
  58706. var particle = this._particles[index];
  58707. this._appendParticleVertices(offset, particle);
  58708. offset += this._useInstancing ? 1 : 4;
  58709. }
  58710. if (this._vertexBuffer) {
  58711. this._vertexBuffer.update(this._vertexData);
  58712. }
  58713. }
  58714. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58715. this.stop();
  58716. }
  58717. };
  58718. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58719. this._appendParticleVertex(offset++, particle, 0, 0);
  58720. if (!this._useInstancing) {
  58721. this._appendParticleVertex(offset++, particle, 1, 0);
  58722. this._appendParticleVertex(offset++, particle, 1, 1);
  58723. this._appendParticleVertex(offset++, particle, 0, 1);
  58724. }
  58725. };
  58726. /**
  58727. * Rebuilds the particle system.
  58728. */
  58729. ParticleSystem.prototype.rebuild = function () {
  58730. this._createIndexBuffer();
  58731. if (this._vertexBuffer) {
  58732. this._vertexBuffer._rebuild();
  58733. }
  58734. };
  58735. /**
  58736. * Is this system ready to be used/rendered
  58737. * @return true if the system is ready
  58738. */
  58739. ParticleSystem.prototype.isReady = function () {
  58740. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58741. return false;
  58742. }
  58743. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58744. if (!this._getEffect(this.blendMode).isReady()) {
  58745. return false;
  58746. }
  58747. }
  58748. else {
  58749. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58750. return false;
  58751. }
  58752. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58753. return false;
  58754. }
  58755. }
  58756. return true;
  58757. };
  58758. ParticleSystem.prototype._render = function (blendMode) {
  58759. var effect = this._getEffect(blendMode);
  58760. var engine = this._scene.getEngine();
  58761. // Render
  58762. engine.enableEffect(effect);
  58763. var viewMatrix = this._scene.getViewMatrix();
  58764. effect.setTexture("diffuseSampler", this.particleTexture);
  58765. effect.setMatrix("view", viewMatrix);
  58766. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58767. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58768. var baseSize = this.particleTexture.getBaseSize();
  58769. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58770. }
  58771. effect.setVector2("translationPivot", this.translationPivot);
  58772. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58773. if (this._isBillboardBased) {
  58774. var camera = this._scene.activeCamera;
  58775. effect.setVector3("eyePosition", camera.globalPosition);
  58776. }
  58777. if (this._rampGradientsTexture) {
  58778. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58779. }
  58780. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58781. var invView = viewMatrix.clone();
  58782. invView.invert();
  58783. effect.setMatrix("invView", invView);
  58784. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58785. }
  58786. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58787. // image processing
  58788. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58789. this._imageProcessingConfiguration.bind(effect);
  58790. }
  58791. // Draw order
  58792. switch (blendMode) {
  58793. case ParticleSystem.BLENDMODE_ADD:
  58794. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58795. break;
  58796. case ParticleSystem.BLENDMODE_ONEONE:
  58797. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58798. break;
  58799. case ParticleSystem.BLENDMODE_STANDARD:
  58800. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58801. break;
  58802. case ParticleSystem.BLENDMODE_MULTIPLY:
  58803. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58804. break;
  58805. }
  58806. if (this._useInstancing) {
  58807. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58808. }
  58809. else {
  58810. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58811. }
  58812. return this._particles.length;
  58813. };
  58814. /**
  58815. * Renders the particle system in its current state.
  58816. * @returns the current number of particles
  58817. */
  58818. ParticleSystem.prototype.render = function () {
  58819. // Check
  58820. if (!this.isReady() || !this._particles.length) {
  58821. return 0;
  58822. }
  58823. var engine = this._scene.getEngine();
  58824. engine.setState(false);
  58825. if (this.forceDepthWrite) {
  58826. engine.setDepthWrite(true);
  58827. }
  58828. var outparticles = 0;
  58829. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58830. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58831. }
  58832. outparticles = this._render(this.blendMode);
  58833. engine.unbindInstanceAttributes();
  58834. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58835. return outparticles;
  58836. };
  58837. /**
  58838. * Disposes the particle system and free the associated resources
  58839. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58840. */
  58841. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58842. if (disposeTexture === void 0) { disposeTexture = true; }
  58843. if (this._vertexBuffer) {
  58844. this._vertexBuffer.dispose();
  58845. this._vertexBuffer = null;
  58846. }
  58847. if (this._spriteBuffer) {
  58848. this._spriteBuffer.dispose();
  58849. this._spriteBuffer = null;
  58850. }
  58851. if (this._indexBuffer) {
  58852. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58853. this._indexBuffer = null;
  58854. }
  58855. if (disposeTexture && this.particleTexture) {
  58856. this.particleTexture.dispose();
  58857. this.particleTexture = null;
  58858. }
  58859. if (disposeTexture && this.noiseTexture) {
  58860. this.noiseTexture.dispose();
  58861. this.noiseTexture = null;
  58862. }
  58863. if (this._rampGradientsTexture) {
  58864. this._rampGradientsTexture.dispose();
  58865. this._rampGradientsTexture = null;
  58866. }
  58867. this._removeFromRoot();
  58868. if (this._subEmitters && this._subEmitters.length) {
  58869. for (var index = 0; index < this._subEmitters.length; index++) {
  58870. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58871. var subEmitter = _a[_i];
  58872. subEmitter.dispose();
  58873. }
  58874. }
  58875. this._subEmitters = [];
  58876. this.subEmitters = [];
  58877. }
  58878. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58879. this.emitter.dispose(true);
  58880. }
  58881. // Remove from scene
  58882. var index = this._scene.particleSystems.indexOf(this);
  58883. if (index > -1) {
  58884. this._scene.particleSystems.splice(index, 1);
  58885. }
  58886. this._scene._activeParticleSystems.dispose();
  58887. // Callback
  58888. this.onDisposeObservable.notifyObservers(this);
  58889. this.onDisposeObservable.clear();
  58890. this.reset();
  58891. };
  58892. // Clone
  58893. /**
  58894. * Clones the particle system.
  58895. * @param name The name of the cloned object
  58896. * @param newEmitter The new emitter to use
  58897. * @returns the cloned particle system
  58898. */
  58899. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58900. var custom = null;
  58901. var program = null;
  58902. if (this.customShader != null) {
  58903. program = this.customShader;
  58904. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58905. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58906. }
  58907. else if (this._customEffect) {
  58908. custom = this._customEffect;
  58909. }
  58910. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58911. result.customShader = program;
  58912. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58913. if (newEmitter === undefined) {
  58914. newEmitter = this.emitter;
  58915. }
  58916. result.noiseTexture = this.noiseTexture;
  58917. result.emitter = newEmitter;
  58918. if (this.particleTexture) {
  58919. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58920. }
  58921. // Clone gradients
  58922. if (this._colorGradients) {
  58923. this._colorGradients.forEach(function (v) {
  58924. result.addColorGradient(v.gradient, v.color1, v.color2);
  58925. });
  58926. }
  58927. if (this._dragGradients) {
  58928. this._dragGradients.forEach(function (v) {
  58929. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58930. });
  58931. }
  58932. if (this._angularSpeedGradients) {
  58933. this._angularSpeedGradients.forEach(function (v) {
  58934. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58935. });
  58936. }
  58937. if (this._emitRateGradients) {
  58938. this._emitRateGradients.forEach(function (v) {
  58939. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58940. });
  58941. }
  58942. if (this._lifeTimeGradients) {
  58943. this._lifeTimeGradients.forEach(function (v) {
  58944. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58945. });
  58946. }
  58947. if (this._limitVelocityGradients) {
  58948. this._limitVelocityGradients.forEach(function (v) {
  58949. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58950. });
  58951. }
  58952. if (this._sizeGradients) {
  58953. this._sizeGradients.forEach(function (v) {
  58954. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58955. });
  58956. }
  58957. if (this._startSizeGradients) {
  58958. this._startSizeGradients.forEach(function (v) {
  58959. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58960. });
  58961. }
  58962. if (this._velocityGradients) {
  58963. this._velocityGradients.forEach(function (v) {
  58964. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58965. });
  58966. }
  58967. if (this._rampGradients) {
  58968. this._rampGradients.forEach(function (v) {
  58969. result.addRampGradient(v.gradient, v.color);
  58970. });
  58971. }
  58972. if (this._colorRemapGradients) {
  58973. this._colorRemapGradients.forEach(function (v) {
  58974. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58975. });
  58976. }
  58977. if (this._alphaRemapGradients) {
  58978. this._alphaRemapGradients.forEach(function (v) {
  58979. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58980. });
  58981. }
  58982. if (!this.preventAutoStart) {
  58983. result.start();
  58984. }
  58985. return result;
  58986. };
  58987. /**
  58988. * Serializes the particle system to a JSON object.
  58989. * @returns the JSON object
  58990. */
  58991. ParticleSystem.prototype.serialize = function () {
  58992. var serializationObject = {};
  58993. ParticleSystem._Serialize(serializationObject, this);
  58994. serializationObject.textureMask = this.textureMask.asArray();
  58995. serializationObject.customShader = this.customShader;
  58996. serializationObject.preventAutoStart = this.preventAutoStart;
  58997. // SubEmitters
  58998. if (this.subEmitters) {
  58999. serializationObject.subEmitters = [];
  59000. if (!this._subEmitters) {
  59001. this._prepareSubEmitterInternalArray();
  59002. }
  59003. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59004. var subs = _a[_i];
  59005. var cell = [];
  59006. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59007. var sub = subs_1[_b];
  59008. cell.push(sub.serialize());
  59009. }
  59010. serializationObject.subEmitters.push(cell);
  59011. }
  59012. }
  59013. return serializationObject;
  59014. };
  59015. /** @hidden */
  59016. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  59017. serializationObject.name = particleSystem.name;
  59018. serializationObject.id = particleSystem.id;
  59019. serializationObject.capacity = particleSystem.getCapacity();
  59020. // Emitter
  59021. if (particleSystem.emitter.position) {
  59022. var emitterMesh = particleSystem.emitter;
  59023. serializationObject.emitterId = emitterMesh.id;
  59024. }
  59025. else {
  59026. var emitterPosition = particleSystem.emitter;
  59027. serializationObject.emitter = emitterPosition.asArray();
  59028. }
  59029. // Emitter
  59030. if (particleSystem.particleEmitterType) {
  59031. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  59032. }
  59033. if (particleSystem.particleTexture) {
  59034. serializationObject.textureName = particleSystem.particleTexture.name;
  59035. serializationObject.invertY = particleSystem.particleTexture._invertY;
  59036. }
  59037. // Animations
  59038. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  59039. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  59040. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  59041. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  59042. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  59043. // Particle system
  59044. serializationObject.startDelay = particleSystem.startDelay;
  59045. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  59046. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  59047. serializationObject.billboardMode = particleSystem.billboardMode;
  59048. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  59049. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  59050. serializationObject.minSize = particleSystem.minSize;
  59051. serializationObject.maxSize = particleSystem.maxSize;
  59052. serializationObject.minScaleX = particleSystem.minScaleX;
  59053. serializationObject.maxScaleX = particleSystem.maxScaleX;
  59054. serializationObject.minScaleY = particleSystem.minScaleY;
  59055. serializationObject.maxScaleY = particleSystem.maxScaleY;
  59056. serializationObject.minEmitPower = particleSystem.minEmitPower;
  59057. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  59058. serializationObject.minLifeTime = particleSystem.minLifeTime;
  59059. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  59060. serializationObject.emitRate = particleSystem.emitRate;
  59061. serializationObject.gravity = particleSystem.gravity.asArray();
  59062. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  59063. serializationObject.color1 = particleSystem.color1.asArray();
  59064. serializationObject.color2 = particleSystem.color2.asArray();
  59065. serializationObject.colorDead = particleSystem.colorDead.asArray();
  59066. serializationObject.updateSpeed = particleSystem.updateSpeed;
  59067. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  59068. serializationObject.blendMode = particleSystem.blendMode;
  59069. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  59070. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  59071. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  59072. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  59073. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  59074. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  59075. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  59076. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  59077. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  59078. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  59079. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  59080. var colorGradients = particleSystem.getColorGradients();
  59081. if (colorGradients) {
  59082. serializationObject.colorGradients = [];
  59083. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  59084. var colorGradient = colorGradients_1[_i];
  59085. var serializedGradient = {
  59086. gradient: colorGradient.gradient,
  59087. color1: colorGradient.color1.asArray()
  59088. };
  59089. if (colorGradient.color2) {
  59090. serializedGradient.color2 = colorGradient.color2.asArray();
  59091. }
  59092. serializationObject.colorGradients.push(serializedGradient);
  59093. }
  59094. }
  59095. var rampGradients = particleSystem.getRampGradients();
  59096. if (rampGradients) {
  59097. serializationObject.rampGradients = [];
  59098. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  59099. var rampGradient = rampGradients_1[_a];
  59100. var serializedGradient = {
  59101. gradient: rampGradient.gradient,
  59102. color: rampGradient.color.asArray()
  59103. };
  59104. serializationObject.rampGradients.push(serializedGradient);
  59105. }
  59106. serializationObject.useRampGradients = particleSystem.useRampGradients;
  59107. }
  59108. var colorRemapGradients = particleSystem.getColorRemapGradients();
  59109. if (colorRemapGradients) {
  59110. serializationObject.colorRemapGradients = [];
  59111. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  59112. var colorRemapGradient = colorRemapGradients_1[_b];
  59113. var serializedGradient = {
  59114. gradient: colorRemapGradient.gradient,
  59115. factor1: colorRemapGradient.factor1
  59116. };
  59117. if (colorRemapGradient.factor2 !== undefined) {
  59118. serializedGradient.factor2 = colorRemapGradient.factor2;
  59119. }
  59120. serializationObject.colorRemapGradients.push(serializedGradient);
  59121. }
  59122. }
  59123. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  59124. if (alphaRemapGradients) {
  59125. serializationObject.alphaRemapGradients = [];
  59126. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  59127. var alphaRemapGradient = alphaRemapGradients_1[_c];
  59128. var serializedGradient = {
  59129. gradient: alphaRemapGradient.gradient,
  59130. factor1: alphaRemapGradient.factor1
  59131. };
  59132. if (alphaRemapGradient.factor2 !== undefined) {
  59133. serializedGradient.factor2 = alphaRemapGradient.factor2;
  59134. }
  59135. serializationObject.alphaRemapGradients.push(serializedGradient);
  59136. }
  59137. }
  59138. var sizeGradients = particleSystem.getSizeGradients();
  59139. if (sizeGradients) {
  59140. serializationObject.sizeGradients = [];
  59141. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  59142. var sizeGradient = sizeGradients_1[_d];
  59143. var serializedGradient = {
  59144. gradient: sizeGradient.gradient,
  59145. factor1: sizeGradient.factor1
  59146. };
  59147. if (sizeGradient.factor2 !== undefined) {
  59148. serializedGradient.factor2 = sizeGradient.factor2;
  59149. }
  59150. serializationObject.sizeGradients.push(serializedGradient);
  59151. }
  59152. }
  59153. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  59154. if (angularSpeedGradients) {
  59155. serializationObject.angularSpeedGradients = [];
  59156. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  59157. var angularSpeedGradient = angularSpeedGradients_1[_e];
  59158. var serializedGradient = {
  59159. gradient: angularSpeedGradient.gradient,
  59160. factor1: angularSpeedGradient.factor1
  59161. };
  59162. if (angularSpeedGradient.factor2 !== undefined) {
  59163. serializedGradient.factor2 = angularSpeedGradient.factor2;
  59164. }
  59165. serializationObject.angularSpeedGradients.push(serializedGradient);
  59166. }
  59167. }
  59168. var velocityGradients = particleSystem.getVelocityGradients();
  59169. if (velocityGradients) {
  59170. serializationObject.velocityGradients = [];
  59171. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  59172. var velocityGradient = velocityGradients_1[_f];
  59173. var serializedGradient = {
  59174. gradient: velocityGradient.gradient,
  59175. factor1: velocityGradient.factor1
  59176. };
  59177. if (velocityGradient.factor2 !== undefined) {
  59178. serializedGradient.factor2 = velocityGradient.factor2;
  59179. }
  59180. serializationObject.velocityGradients.push(serializedGradient);
  59181. }
  59182. }
  59183. var dragGradients = particleSystem.getDragGradients();
  59184. if (dragGradients) {
  59185. serializationObject.dragyGradients = [];
  59186. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  59187. var dragGradient = dragGradients_1[_g];
  59188. var serializedGradient = {
  59189. gradient: dragGradient.gradient,
  59190. factor1: dragGradient.factor1
  59191. };
  59192. if (dragGradient.factor2 !== undefined) {
  59193. serializedGradient.factor2 = dragGradient.factor2;
  59194. }
  59195. serializationObject.dragGradients.push(serializedGradient);
  59196. }
  59197. }
  59198. var emitRateGradients = particleSystem.getEmitRateGradients();
  59199. if (emitRateGradients) {
  59200. serializationObject.emitRateGradients = [];
  59201. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  59202. var emitRateGradient = emitRateGradients_1[_h];
  59203. var serializedGradient = {
  59204. gradient: emitRateGradient.gradient,
  59205. factor1: emitRateGradient.factor1
  59206. };
  59207. if (emitRateGradient.factor2 !== undefined) {
  59208. serializedGradient.factor2 = emitRateGradient.factor2;
  59209. }
  59210. serializationObject.emitRateGradients.push(serializedGradient);
  59211. }
  59212. }
  59213. var startSizeGradients = particleSystem.getStartSizeGradients();
  59214. if (startSizeGradients) {
  59215. serializationObject.startSizeGradients = [];
  59216. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  59217. var startSizeGradient = startSizeGradients_1[_j];
  59218. var serializedGradient = {
  59219. gradient: startSizeGradient.gradient,
  59220. factor1: startSizeGradient.factor1
  59221. };
  59222. if (startSizeGradient.factor2 !== undefined) {
  59223. serializedGradient.factor2 = startSizeGradient.factor2;
  59224. }
  59225. serializationObject.startSizeGradients.push(serializedGradient);
  59226. }
  59227. }
  59228. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  59229. if (lifeTimeGradients) {
  59230. serializationObject.lifeTimeGradients = [];
  59231. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  59232. var lifeTimeGradient = lifeTimeGradients_1[_k];
  59233. var serializedGradient = {
  59234. gradient: lifeTimeGradient.gradient,
  59235. factor1: lifeTimeGradient.factor1
  59236. };
  59237. if (lifeTimeGradient.factor2 !== undefined) {
  59238. serializedGradient.factor2 = lifeTimeGradient.factor2;
  59239. }
  59240. serializationObject.lifeTimeGradients.push(serializedGradient);
  59241. }
  59242. }
  59243. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  59244. if (limitVelocityGradients) {
  59245. serializationObject.limitVelocityGradients = [];
  59246. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  59247. var limitVelocityGradient = limitVelocityGradients_1[_l];
  59248. var serializedGradient = {
  59249. gradient: limitVelocityGradient.gradient,
  59250. factor1: limitVelocityGradient.factor1
  59251. };
  59252. if (limitVelocityGradient.factor2 !== undefined) {
  59253. serializedGradient.factor2 = limitVelocityGradient.factor2;
  59254. }
  59255. serializationObject.limitVelocityGradients.push(serializedGradient);
  59256. }
  59257. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  59258. }
  59259. if (particleSystem.noiseTexture) {
  59260. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  59261. }
  59262. };
  59263. /** @hidden */
  59264. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  59265. // Texture
  59266. if (parsedParticleSystem.textureName) {
  59267. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  59268. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  59269. }
  59270. // Emitter
  59271. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  59272. particleSystem.emitter = BABYLON.Vector3.Zero();
  59273. }
  59274. else if (parsedParticleSystem.emitterId) {
  59275. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  59276. }
  59277. else {
  59278. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  59279. }
  59280. // Misc.
  59281. if (parsedParticleSystem.renderingGroupId !== undefined) {
  59282. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  59283. }
  59284. if (parsedParticleSystem.isBillboardBased !== undefined) {
  59285. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  59286. }
  59287. if (parsedParticleSystem.billboardMode !== undefined) {
  59288. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  59289. }
  59290. // Animations
  59291. if (parsedParticleSystem.animations) {
  59292. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  59293. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  59294. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59295. }
  59296. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  59297. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  59298. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  59299. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  59300. }
  59301. if (parsedParticleSystem.autoAnimate) {
  59302. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  59303. }
  59304. // Particle system
  59305. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  59306. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  59307. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  59308. particleSystem.minSize = parsedParticleSystem.minSize;
  59309. particleSystem.maxSize = parsedParticleSystem.maxSize;
  59310. if (parsedParticleSystem.minScaleX) {
  59311. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59312. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59313. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59314. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59315. }
  59316. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59317. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59318. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59319. }
  59320. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59321. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59322. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59323. }
  59324. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59325. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59326. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59327. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59328. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59329. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59330. if (parsedParticleSystem.noiseStrength) {
  59331. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59332. }
  59333. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59334. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59335. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59336. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59337. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59338. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59339. if (parsedParticleSystem.colorGradients) {
  59340. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59341. var colorGradient = _a[_i];
  59342. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59343. }
  59344. }
  59345. if (parsedParticleSystem.rampGradients) {
  59346. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59347. var rampGradient = _c[_b];
  59348. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  59349. }
  59350. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  59351. }
  59352. if (parsedParticleSystem.colorRemapGradients) {
  59353. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59354. var colorRemapGradient = _e[_d];
  59355. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59356. }
  59357. }
  59358. if (parsedParticleSystem.alphaRemapGradients) {
  59359. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59360. var alphaRemapGradient = _g[_f];
  59361. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59362. }
  59363. }
  59364. if (parsedParticleSystem.sizeGradients) {
  59365. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59366. var sizeGradient = _j[_h];
  59367. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59368. }
  59369. }
  59370. if (parsedParticleSystem.sizeGradients) {
  59371. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59372. var sizeGradient = _l[_k];
  59373. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59374. }
  59375. }
  59376. if (parsedParticleSystem.angularSpeedGradients) {
  59377. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59378. var angularSpeedGradient = _o[_m];
  59379. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59380. }
  59381. }
  59382. if (parsedParticleSystem.velocityGradients) {
  59383. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59384. var velocityGradient = _q[_p];
  59385. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59386. }
  59387. }
  59388. if (parsedParticleSystem.dragGradients) {
  59389. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59390. var dragGradient = _s[_r];
  59391. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59392. }
  59393. }
  59394. if (parsedParticleSystem.emitRateGradients) {
  59395. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59396. var emitRateGradient = _u[_t];
  59397. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59398. }
  59399. }
  59400. if (parsedParticleSystem.startSizeGradients) {
  59401. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59402. var startSizeGradient = _w[_v];
  59403. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59404. }
  59405. }
  59406. if (parsedParticleSystem.lifeTimeGradients) {
  59407. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  59408. var lifeTimeGradient = _y[_x];
  59409. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  59410. }
  59411. }
  59412. if (parsedParticleSystem.limitVelocityGradients) {
  59413. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  59414. var limitVelocityGradient = _0[_z];
  59415. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59416. }
  59417. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59418. }
  59419. if (parsedParticleSystem.noiseTexture) {
  59420. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59421. }
  59422. // Emitter
  59423. var emitterType;
  59424. if (parsedParticleSystem.particleEmitterType) {
  59425. switch (parsedParticleSystem.particleEmitterType.type) {
  59426. case "SphereParticleEmitter":
  59427. emitterType = new BABYLON.SphereParticleEmitter();
  59428. break;
  59429. case "SphereDirectedParticleEmitter":
  59430. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59431. break;
  59432. case "ConeEmitter":
  59433. case "ConeParticleEmitter":
  59434. emitterType = new BABYLON.ConeParticleEmitter();
  59435. break;
  59436. case "CylinderParticleEmitter":
  59437. emitterType = new BABYLON.CylinderParticleEmitter();
  59438. break;
  59439. case "HemisphericParticleEmitter":
  59440. emitterType = new BABYLON.HemisphericParticleEmitter();
  59441. break;
  59442. case "BoxEmitter":
  59443. case "BoxParticleEmitter":
  59444. default:
  59445. emitterType = new BABYLON.BoxParticleEmitter();
  59446. break;
  59447. }
  59448. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59449. }
  59450. else {
  59451. emitterType = new BABYLON.BoxParticleEmitter();
  59452. emitterType.parse(parsedParticleSystem);
  59453. }
  59454. particleSystem.particleEmitterType = emitterType;
  59455. // Animation sheet
  59456. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59457. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59458. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59459. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59460. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59461. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  59462. };
  59463. /**
  59464. * Parses a JSON object to create a particle system.
  59465. * @param parsedParticleSystem The JSON object to parse
  59466. * @param scene The scene to create the particle system in
  59467. * @param rootUrl The root url to use to load external dependencies like texture
  59468. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  59469. * @returns the Parsed particle system
  59470. */
  59471. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  59472. if (doNotStart === void 0) { doNotStart = false; }
  59473. var name = parsedParticleSystem.name;
  59474. var custom = null;
  59475. var program = null;
  59476. if (parsedParticleSystem.customShader) {
  59477. program = parsedParticleSystem.customShader;
  59478. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59479. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59480. }
  59481. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59482. particleSystem.customShader = program;
  59483. if (parsedParticleSystem.id) {
  59484. particleSystem.id = parsedParticleSystem.id;
  59485. }
  59486. // SubEmitters
  59487. if (parsedParticleSystem.subEmitters) {
  59488. particleSystem.subEmitters = [];
  59489. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  59490. var cell = _a[_i];
  59491. var cellArray = [];
  59492. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  59493. var sub = cell_1[_b];
  59494. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  59495. }
  59496. particleSystem.subEmitters.push(cellArray);
  59497. }
  59498. }
  59499. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59500. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59501. // Auto start
  59502. if (parsedParticleSystem.preventAutoStart) {
  59503. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59504. }
  59505. if (!doNotStart && !particleSystem.preventAutoStart) {
  59506. particleSystem.start();
  59507. }
  59508. return particleSystem;
  59509. };
  59510. /**
  59511. * Billboard mode will only apply to Y axis
  59512. */
  59513. ParticleSystem.BILLBOARDMODE_Y = 2;
  59514. /**
  59515. * Billboard mode will apply to all axes
  59516. */
  59517. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59518. /**
  59519. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59520. */
  59521. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59522. return ParticleSystem;
  59523. }(BABYLON.BaseParticleSystem));
  59524. BABYLON.ParticleSystem = ParticleSystem;
  59525. })(BABYLON || (BABYLON = {}));
  59526. //# sourceMappingURL=babylon.particleSystem.js.map
  59527. var BABYLON;
  59528. (function (BABYLON) {
  59529. /**
  59530. * Particle emitter emitting particles from the inside of a box.
  59531. * It emits the particles randomly between 2 given directions.
  59532. */
  59533. var BoxParticleEmitter = /** @class */ (function () {
  59534. /**
  59535. * Creates a new instance BoxParticleEmitter
  59536. */
  59537. function BoxParticleEmitter() {
  59538. /**
  59539. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59540. */
  59541. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59542. /**
  59543. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59544. */
  59545. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59546. /**
  59547. * 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.
  59548. */
  59549. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59550. /**
  59551. * 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.
  59552. */
  59553. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59554. }
  59555. /**
  59556. * Called by the particle System when the direction is computed for the created particle.
  59557. * @param worldMatrix is the world matrix of the particle system
  59558. * @param directionToUpdate is the direction vector to update with the result
  59559. * @param particle is the particle we are computed the direction for
  59560. */
  59561. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59562. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59563. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59564. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59565. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59566. };
  59567. /**
  59568. * Called by the particle System when the position is computed for the created particle.
  59569. * @param worldMatrix is the world matrix of the particle system
  59570. * @param positionToUpdate is the position vector to update with the result
  59571. * @param particle is the particle we are computed the position for
  59572. */
  59573. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59574. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59575. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59576. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59577. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59578. };
  59579. /**
  59580. * Clones the current emitter and returns a copy of it
  59581. * @returns the new emitter
  59582. */
  59583. BoxParticleEmitter.prototype.clone = function () {
  59584. var newOne = new BoxParticleEmitter();
  59585. BABYLON.Tools.DeepCopy(this, newOne);
  59586. return newOne;
  59587. };
  59588. /**
  59589. * Called by the GPUParticleSystem to setup the update shader
  59590. * @param effect defines the update shader
  59591. */
  59592. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59593. effect.setVector3("direction1", this.direction1);
  59594. effect.setVector3("direction2", this.direction2);
  59595. effect.setVector3("minEmitBox", this.minEmitBox);
  59596. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59597. };
  59598. /**
  59599. * Returns a string to use to update the GPU particles update shader
  59600. * @returns a string containng the defines string
  59601. */
  59602. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59603. return "#define BOXEMITTER";
  59604. };
  59605. /**
  59606. * Returns the string "BoxParticleEmitter"
  59607. * @returns a string containing the class name
  59608. */
  59609. BoxParticleEmitter.prototype.getClassName = function () {
  59610. return "BoxParticleEmitter";
  59611. };
  59612. /**
  59613. * Serializes the particle system to a JSON object.
  59614. * @returns the JSON object
  59615. */
  59616. BoxParticleEmitter.prototype.serialize = function () {
  59617. var serializationObject = {};
  59618. serializationObject.type = this.getClassName();
  59619. serializationObject.direction1 = this.direction1.asArray();
  59620. serializationObject.direction2 = this.direction2.asArray();
  59621. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59622. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59623. return serializationObject;
  59624. };
  59625. /**
  59626. * Parse properties from a JSON object
  59627. * @param serializationObject defines the JSON object
  59628. */
  59629. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59630. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59631. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59632. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59633. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59634. };
  59635. return BoxParticleEmitter;
  59636. }());
  59637. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59638. })(BABYLON || (BABYLON = {}));
  59639. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59640. var BABYLON;
  59641. (function (BABYLON) {
  59642. /**
  59643. * Particle emitter emitting particles from the inside of a cylinder.
  59644. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59645. */
  59646. var CylinderParticleEmitter = /** @class */ (function () {
  59647. /**
  59648. * Creates a new instance CylinderParticleEmitter
  59649. * @param radius the radius of the emission cylinder (1 by default)
  59650. * @param height the height of the emission cylinder (1 by default)
  59651. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59652. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59653. */
  59654. function CylinderParticleEmitter(
  59655. /**
  59656. * The radius of the emission cylinder.
  59657. */
  59658. radius,
  59659. /**
  59660. * The height of the emission cylinder.
  59661. */
  59662. height,
  59663. /**
  59664. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59665. */
  59666. radiusRange,
  59667. /**
  59668. * How much to randomize the particle direction [0-1].
  59669. */
  59670. directionRandomizer) {
  59671. if (radius === void 0) { radius = 1; }
  59672. if (height === void 0) { height = 1; }
  59673. if (radiusRange === void 0) { radiusRange = 1; }
  59674. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59675. this.radius = radius;
  59676. this.height = height;
  59677. this.radiusRange = radiusRange;
  59678. this.directionRandomizer = directionRandomizer;
  59679. }
  59680. /**
  59681. * Called by the particle System when the direction is computed for the created particle.
  59682. * @param worldMatrix is the world matrix of the particle system
  59683. * @param directionToUpdate is the direction vector to update with the result
  59684. * @param particle is the particle we are computed the direction for
  59685. */
  59686. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59687. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59688. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59689. var angle = Math.atan2(direction.x, direction.z);
  59690. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59691. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59692. direction.x = Math.sin(angle);
  59693. direction.z = Math.cos(angle);
  59694. direction.normalize();
  59695. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59696. };
  59697. /**
  59698. * Called by the particle System when the position is computed for the created particle.
  59699. * @param worldMatrix is the world matrix of the particle system
  59700. * @param positionToUpdate is the position vector to update with the result
  59701. * @param particle is the particle we are computed the position for
  59702. */
  59703. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59704. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59705. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59706. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59707. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59708. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59709. var xPos = positionRadius * Math.cos(angle);
  59710. var zPos = positionRadius * Math.sin(angle);
  59711. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59712. };
  59713. /**
  59714. * Clones the current emitter and returns a copy of it
  59715. * @returns the new emitter
  59716. */
  59717. CylinderParticleEmitter.prototype.clone = function () {
  59718. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59719. BABYLON.Tools.DeepCopy(this, newOne);
  59720. return newOne;
  59721. };
  59722. /**
  59723. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59724. * @param effect defines the update shader
  59725. */
  59726. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59727. effect.setFloat("radius", this.radius);
  59728. effect.setFloat("height", this.height);
  59729. effect.setFloat("radiusRange", this.radiusRange);
  59730. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59731. };
  59732. /**
  59733. * Returns a string to use to update the GPU particles update shader
  59734. * @returns a string containng the defines string
  59735. */
  59736. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59737. return "#define CYLINDEREMITTER";
  59738. };
  59739. /**
  59740. * Returns the string "CylinderParticleEmitter"
  59741. * @returns a string containing the class name
  59742. */
  59743. CylinderParticleEmitter.prototype.getClassName = function () {
  59744. return "CylinderParticleEmitter";
  59745. };
  59746. /**
  59747. * Serializes the particle system to a JSON object.
  59748. * @returns the JSON object
  59749. */
  59750. CylinderParticleEmitter.prototype.serialize = function () {
  59751. var serializationObject = {};
  59752. serializationObject.type = this.getClassName();
  59753. serializationObject.radius = this.radius;
  59754. serializationObject.height = this.height;
  59755. serializationObject.radiusRange = this.radiusRange;
  59756. serializationObject.directionRandomizer = this.directionRandomizer;
  59757. return serializationObject;
  59758. };
  59759. /**
  59760. * Parse properties from a JSON object
  59761. * @param serializationObject defines the JSON object
  59762. */
  59763. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59764. this.radius = serializationObject.radius;
  59765. this.height = serializationObject.height;
  59766. this.radiusRange = serializationObject.radiusRange;
  59767. this.directionRandomizer = serializationObject.directionRandomizer;
  59768. };
  59769. return CylinderParticleEmitter;
  59770. }());
  59771. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59772. /**
  59773. * Particle emitter emitting particles from the inside of a cylinder.
  59774. * It emits the particles randomly between two vectors.
  59775. */
  59776. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59777. __extends(CylinderDirectedParticleEmitter, _super);
  59778. /**
  59779. * Creates a new instance CylinderDirectedParticleEmitter
  59780. * @param radius the radius of the emission cylinder (1 by default)
  59781. * @param height the height of the emission cylinder (1 by default)
  59782. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59783. * @param direction1 the min limit of the emission direction (up vector by default)
  59784. * @param direction2 the max limit of the emission direction (up vector by default)
  59785. */
  59786. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59787. /**
  59788. * The min limit of the emission direction.
  59789. */
  59790. direction1,
  59791. /**
  59792. * The max limit of the emission direction.
  59793. */
  59794. direction2) {
  59795. if (radius === void 0) { radius = 1; }
  59796. if (height === void 0) { height = 1; }
  59797. if (radiusRange === void 0) { radiusRange = 1; }
  59798. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59799. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59800. var _this = _super.call(this, radius, height, radiusRange) || this;
  59801. _this.direction1 = direction1;
  59802. _this.direction2 = direction2;
  59803. return _this;
  59804. }
  59805. /**
  59806. * Called by the particle System when the direction is computed for the created particle.
  59807. * @param worldMatrix is the world matrix of the particle system
  59808. * @param directionToUpdate is the direction vector to update with the result
  59809. * @param particle is the particle we are computed the direction for
  59810. */
  59811. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59812. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59813. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59814. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59815. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59816. };
  59817. /**
  59818. * Clones the current emitter and returns a copy of it
  59819. * @returns the new emitter
  59820. */
  59821. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59822. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59823. BABYLON.Tools.DeepCopy(this, newOne);
  59824. return newOne;
  59825. };
  59826. /**
  59827. * Called by the GPUParticleSystem to setup the update shader
  59828. * @param effect defines the update shader
  59829. */
  59830. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59831. effect.setFloat("radius", this.radius);
  59832. effect.setFloat("height", this.height);
  59833. effect.setFloat("radiusRange", this.radiusRange);
  59834. effect.setVector3("direction1", this.direction1);
  59835. effect.setVector3("direction2", this.direction2);
  59836. };
  59837. /**
  59838. * Returns a string to use to update the GPU particles update shader
  59839. * @returns a string containng the defines string
  59840. */
  59841. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59842. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59843. };
  59844. /**
  59845. * Returns the string "CylinderDirectedParticleEmitter"
  59846. * @returns a string containing the class name
  59847. */
  59848. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59849. return "CylinderDirectedParticleEmitter";
  59850. };
  59851. /**
  59852. * Serializes the particle system to a JSON object.
  59853. * @returns the JSON object
  59854. */
  59855. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59856. var serializationObject = _super.prototype.serialize.call(this);
  59857. serializationObject.direction1 = this.direction1.asArray();
  59858. serializationObject.direction2 = this.direction2.asArray();
  59859. return serializationObject;
  59860. };
  59861. /**
  59862. * Parse properties from a JSON object
  59863. * @param serializationObject defines the JSON object
  59864. */
  59865. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59866. _super.prototype.parse.call(this, serializationObject);
  59867. this.direction1.copyFrom(serializationObject.direction1);
  59868. this.direction2.copyFrom(serializationObject.direction2);
  59869. };
  59870. return CylinderDirectedParticleEmitter;
  59871. }(CylinderParticleEmitter));
  59872. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59873. })(BABYLON || (BABYLON = {}));
  59874. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59875. var BABYLON;
  59876. (function (BABYLON) {
  59877. /**
  59878. * Particle emitter emitting particles from the inside of a cone.
  59879. * It emits the particles alongside the cone volume from the base to the particle.
  59880. * The emission direction might be randomized.
  59881. */
  59882. var ConeParticleEmitter = /** @class */ (function () {
  59883. /**
  59884. * Creates a new instance ConeParticleEmitter
  59885. * @param radius the radius of the emission cone (1 by default)
  59886. * @param angles the cone base angle (PI by default)
  59887. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59888. */
  59889. function ConeParticleEmitter(radius, angle,
  59890. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59891. directionRandomizer) {
  59892. if (radius === void 0) { radius = 1; }
  59893. if (angle === void 0) { angle = Math.PI; }
  59894. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59895. this.directionRandomizer = directionRandomizer;
  59896. /**
  59897. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59898. */
  59899. this.radiusRange = 1;
  59900. /**
  59901. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59902. */
  59903. this.heightRange = 1;
  59904. /**
  59905. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59906. */
  59907. this.emitFromSpawnPointOnly = false;
  59908. this.angle = angle;
  59909. this.radius = radius;
  59910. }
  59911. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59912. /**
  59913. * Gets or sets the radius of the emission cone
  59914. */
  59915. get: function () {
  59916. return this._radius;
  59917. },
  59918. set: function (value) {
  59919. this._radius = value;
  59920. this._buildHeight();
  59921. },
  59922. enumerable: true,
  59923. configurable: true
  59924. });
  59925. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59926. /**
  59927. * Gets or sets the angle of the emission cone
  59928. */
  59929. get: function () {
  59930. return this._angle;
  59931. },
  59932. set: function (value) {
  59933. this._angle = value;
  59934. this._buildHeight();
  59935. },
  59936. enumerable: true,
  59937. configurable: true
  59938. });
  59939. ConeParticleEmitter.prototype._buildHeight = function () {
  59940. if (this._angle !== 0) {
  59941. this._height = this._radius / Math.tan(this._angle / 2);
  59942. }
  59943. else {
  59944. this._height = 1;
  59945. }
  59946. };
  59947. /**
  59948. * Called by the particle System when the direction is computed for the created particle.
  59949. * @param worldMatrix is the world matrix of the particle system
  59950. * @param directionToUpdate is the direction vector to update with the result
  59951. * @param particle is the particle we are computed the direction for
  59952. */
  59953. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59954. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59955. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59956. }
  59957. else {
  59958. // measure the direction Vector from the emitter to the particle.
  59959. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59960. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59961. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59962. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59963. direction.x += randX;
  59964. direction.y += randY;
  59965. direction.z += randZ;
  59966. direction.normalize();
  59967. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59968. }
  59969. };
  59970. /**
  59971. * Called by the particle System when the position is computed for the created particle.
  59972. * @param worldMatrix is the world matrix of the particle system
  59973. * @param positionToUpdate is the position vector to update with the result
  59974. * @param particle is the particle we are computed the position for
  59975. */
  59976. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59977. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59978. var h;
  59979. if (!this.emitFromSpawnPointOnly) {
  59980. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59981. // Better distribution in a cone at normal angles.
  59982. h = 1 - h * h;
  59983. }
  59984. else {
  59985. h = 0.0001;
  59986. }
  59987. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59988. radius = radius * h;
  59989. var randX = radius * Math.sin(s);
  59990. var randZ = radius * Math.cos(s);
  59991. var randY = h * this._height;
  59992. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59993. };
  59994. /**
  59995. * Clones the current emitter and returns a copy of it
  59996. * @returns the new emitter
  59997. */
  59998. ConeParticleEmitter.prototype.clone = function () {
  59999. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60000. BABYLON.Tools.DeepCopy(this, newOne);
  60001. return newOne;
  60002. };
  60003. /**
  60004. * Called by the GPUParticleSystem to setup the update shader
  60005. * @param effect defines the update shader
  60006. */
  60007. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60008. effect.setFloat2("radius", this._radius, this.radiusRange);
  60009. effect.setFloat("coneAngle", this._angle);
  60010. effect.setFloat2("height", this._height, this.heightRange);
  60011. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60012. };
  60013. /**
  60014. * Returns a string to use to update the GPU particles update shader
  60015. * @returns a string containng the defines string
  60016. */
  60017. ConeParticleEmitter.prototype.getEffectDefines = function () {
  60018. var defines = "#define CONEEMITTER";
  60019. if (this.emitFromSpawnPointOnly) {
  60020. defines += "\n#define CONEEMITTERSPAWNPOINT";
  60021. }
  60022. return defines;
  60023. };
  60024. /**
  60025. * Returns the string "ConeParticleEmitter"
  60026. * @returns a string containing the class name
  60027. */
  60028. ConeParticleEmitter.prototype.getClassName = function () {
  60029. return "ConeParticleEmitter";
  60030. };
  60031. /**
  60032. * Serializes the particle system to a JSON object.
  60033. * @returns the JSON object
  60034. */
  60035. ConeParticleEmitter.prototype.serialize = function () {
  60036. var serializationObject = {};
  60037. serializationObject.type = this.getClassName();
  60038. serializationObject.radius = this._radius;
  60039. serializationObject.angle = this._angle;
  60040. serializationObject.directionRandomizer = this.directionRandomizer;
  60041. return serializationObject;
  60042. };
  60043. /**
  60044. * Parse properties from a JSON object
  60045. * @param serializationObject defines the JSON object
  60046. */
  60047. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  60048. this.radius = serializationObject.radius;
  60049. this.angle = serializationObject.angle;
  60050. this.directionRandomizer = serializationObject.directionRandomizer;
  60051. };
  60052. return ConeParticleEmitter;
  60053. }());
  60054. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  60055. })(BABYLON || (BABYLON = {}));
  60056. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  60057. var BABYLON;
  60058. (function (BABYLON) {
  60059. /**
  60060. * Particle emitter emitting particles from the inside of a sphere.
  60061. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  60062. */
  60063. var SphereParticleEmitter = /** @class */ (function () {
  60064. /**
  60065. * Creates a new instance SphereParticleEmitter
  60066. * @param radius the radius of the emission sphere (1 by default)
  60067. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60068. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60069. */
  60070. function SphereParticleEmitter(
  60071. /**
  60072. * The radius of the emission sphere.
  60073. */
  60074. radius,
  60075. /**
  60076. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60077. */
  60078. radiusRange,
  60079. /**
  60080. * How much to randomize the particle direction [0-1].
  60081. */
  60082. directionRandomizer) {
  60083. if (radius === void 0) { radius = 1; }
  60084. if (radiusRange === void 0) { radiusRange = 1; }
  60085. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60086. this.radius = radius;
  60087. this.radiusRange = radiusRange;
  60088. this.directionRandomizer = directionRandomizer;
  60089. }
  60090. /**
  60091. * Called by the particle System when the direction is computed for the created particle.
  60092. * @param worldMatrix is the world matrix of the particle system
  60093. * @param directionToUpdate is the direction vector to update with the result
  60094. * @param particle is the particle we are computed the direction for
  60095. */
  60096. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60097. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60098. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60099. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60100. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60101. direction.x += randX;
  60102. direction.y += randY;
  60103. direction.z += randZ;
  60104. direction.normalize();
  60105. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60106. };
  60107. /**
  60108. * Called by the particle System when the position is computed for the created particle.
  60109. * @param worldMatrix is the world matrix of the particle system
  60110. * @param positionToUpdate is the position vector to update with the result
  60111. * @param particle is the particle we are computed the position for
  60112. */
  60113. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60114. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60115. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60116. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60117. var theta = Math.acos(2 * v - 1);
  60118. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60119. var randY = randRadius * Math.cos(theta);
  60120. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60121. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60122. };
  60123. /**
  60124. * Clones the current emitter and returns a copy of it
  60125. * @returns the new emitter
  60126. */
  60127. SphereParticleEmitter.prototype.clone = function () {
  60128. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  60129. BABYLON.Tools.DeepCopy(this, newOne);
  60130. return newOne;
  60131. };
  60132. /**
  60133. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60134. * @param effect defines the update shader
  60135. */
  60136. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  60137. effect.setFloat("radius", this.radius);
  60138. effect.setFloat("radiusRange", this.radiusRange);
  60139. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60140. };
  60141. /**
  60142. * Returns a string to use to update the GPU particles update shader
  60143. * @returns a string containng the defines string
  60144. */
  60145. SphereParticleEmitter.prototype.getEffectDefines = function () {
  60146. return "#define SPHEREEMITTER";
  60147. };
  60148. /**
  60149. * Returns the string "SphereParticleEmitter"
  60150. * @returns a string containing the class name
  60151. */
  60152. SphereParticleEmitter.prototype.getClassName = function () {
  60153. return "SphereParticleEmitter";
  60154. };
  60155. /**
  60156. * Serializes the particle system to a JSON object.
  60157. * @returns the JSON object
  60158. */
  60159. SphereParticleEmitter.prototype.serialize = function () {
  60160. var serializationObject = {};
  60161. serializationObject.type = this.getClassName();
  60162. serializationObject.radius = this.radius;
  60163. serializationObject.radiusRange = this.radiusRange;
  60164. serializationObject.directionRandomizer = this.directionRandomizer;
  60165. return serializationObject;
  60166. };
  60167. /**
  60168. * Parse properties from a JSON object
  60169. * @param serializationObject defines the JSON object
  60170. */
  60171. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  60172. this.radius = serializationObject.radius;
  60173. this.radiusRange = serializationObject.radiusRange;
  60174. this.directionRandomizer = serializationObject.directionRandomizer;
  60175. };
  60176. return SphereParticleEmitter;
  60177. }());
  60178. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  60179. /**
  60180. * Particle emitter emitting particles from the inside of a sphere.
  60181. * It emits the particles randomly between two vectors.
  60182. */
  60183. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  60184. __extends(SphereDirectedParticleEmitter, _super);
  60185. /**
  60186. * Creates a new instance SphereDirectedParticleEmitter
  60187. * @param radius the radius of the emission sphere (1 by default)
  60188. * @param direction1 the min limit of the emission direction (up vector by default)
  60189. * @param direction2 the max limit of the emission direction (up vector by default)
  60190. */
  60191. function SphereDirectedParticleEmitter(radius,
  60192. /**
  60193. * The min limit of the emission direction.
  60194. */
  60195. direction1,
  60196. /**
  60197. * The max limit of the emission direction.
  60198. */
  60199. direction2) {
  60200. if (radius === void 0) { radius = 1; }
  60201. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60202. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60203. var _this = _super.call(this, radius) || this;
  60204. _this.direction1 = direction1;
  60205. _this.direction2 = direction2;
  60206. return _this;
  60207. }
  60208. /**
  60209. * Called by the particle System when the direction is computed for the created particle.
  60210. * @param worldMatrix is the world matrix of the particle system
  60211. * @param directionToUpdate is the direction vector to update with the result
  60212. * @param particle is the particle we are computed the direction for
  60213. */
  60214. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60215. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60216. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60217. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60218. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60219. };
  60220. /**
  60221. * Clones the current emitter and returns a copy of it
  60222. * @returns the new emitter
  60223. */
  60224. SphereDirectedParticleEmitter.prototype.clone = function () {
  60225. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  60226. BABYLON.Tools.DeepCopy(this, newOne);
  60227. return newOne;
  60228. };
  60229. /**
  60230. * Called by the GPUParticleSystem to setup the update shader
  60231. * @param effect defines the update shader
  60232. */
  60233. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60234. effect.setFloat("radius", this.radius);
  60235. effect.setFloat("radiusRange", this.radiusRange);
  60236. effect.setVector3("direction1", this.direction1);
  60237. effect.setVector3("direction2", this.direction2);
  60238. };
  60239. /**
  60240. * Returns a string to use to update the GPU particles update shader
  60241. * @returns a string containng the defines string
  60242. */
  60243. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60244. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  60245. };
  60246. /**
  60247. * Returns the string "SphereDirectedParticleEmitter"
  60248. * @returns a string containing the class name
  60249. */
  60250. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  60251. return "SphereDirectedParticleEmitter";
  60252. };
  60253. /**
  60254. * Serializes the particle system to a JSON object.
  60255. * @returns the JSON object
  60256. */
  60257. SphereDirectedParticleEmitter.prototype.serialize = function () {
  60258. var serializationObject = _super.prototype.serialize.call(this);
  60259. serializationObject.direction1 = this.direction1.asArray();
  60260. serializationObject.direction2 = this.direction2.asArray();
  60261. return serializationObject;
  60262. };
  60263. /**
  60264. * Parse properties from a JSON object
  60265. * @param serializationObject defines the JSON object
  60266. */
  60267. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60268. _super.prototype.parse.call(this, serializationObject);
  60269. this.direction1.copyFrom(serializationObject.direction1);
  60270. this.direction2.copyFrom(serializationObject.direction2);
  60271. };
  60272. return SphereDirectedParticleEmitter;
  60273. }(SphereParticleEmitter));
  60274. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  60275. })(BABYLON || (BABYLON = {}));
  60276. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  60277. var BABYLON;
  60278. (function (BABYLON) {
  60279. /**
  60280. * Particle emitter emitting particles from the inside of a hemisphere.
  60281. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  60282. */
  60283. var HemisphericParticleEmitter = /** @class */ (function () {
  60284. /**
  60285. * Creates a new instance HemisphericParticleEmitter
  60286. * @param radius the radius of the emission hemisphere (1 by default)
  60287. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60288. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60289. */
  60290. function HemisphericParticleEmitter(
  60291. /**
  60292. * The radius of the emission hemisphere.
  60293. */
  60294. radius,
  60295. /**
  60296. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60297. */
  60298. radiusRange,
  60299. /**
  60300. * How much to randomize the particle direction [0-1].
  60301. */
  60302. directionRandomizer) {
  60303. if (radius === void 0) { radius = 1; }
  60304. if (radiusRange === void 0) { radiusRange = 1; }
  60305. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60306. this.radius = radius;
  60307. this.radiusRange = radiusRange;
  60308. this.directionRandomizer = directionRandomizer;
  60309. }
  60310. /**
  60311. * Called by the particle System when the direction is computed for the created particle.
  60312. * @param worldMatrix is the world matrix of the particle system
  60313. * @param directionToUpdate is the direction vector to update with the result
  60314. * @param particle is the particle we are computed the direction for
  60315. */
  60316. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60317. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60318. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60319. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60320. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60321. direction.x += randX;
  60322. direction.y += randY;
  60323. direction.z += randZ;
  60324. direction.normalize();
  60325. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60326. };
  60327. /**
  60328. * Called by the particle System when the position is computed for the created particle.
  60329. * @param worldMatrix is the world matrix of the particle system
  60330. * @param positionToUpdate is the position vector to update with the result
  60331. * @param particle is the particle we are computed the position for
  60332. */
  60333. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60334. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  60335. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  60336. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60337. var theta = Math.acos(2 * v - 1);
  60338. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  60339. var randY = randRadius * Math.cos(theta);
  60340. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60341. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60342. };
  60343. /**
  60344. * Clones the current emitter and returns a copy of it
  60345. * @returns the new emitter
  60346. */
  60347. HemisphericParticleEmitter.prototype.clone = function () {
  60348. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60349. BABYLON.Tools.DeepCopy(this, newOne);
  60350. return newOne;
  60351. };
  60352. /**
  60353. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60354. * @param effect defines the update shader
  60355. */
  60356. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60357. effect.setFloat("radius", this.radius);
  60358. effect.setFloat("radiusRange", this.radiusRange);
  60359. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60360. };
  60361. /**
  60362. * Returns a string to use to update the GPU particles update shader
  60363. * @returns a string containng the defines string
  60364. */
  60365. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60366. return "#define HEMISPHERICEMITTER";
  60367. };
  60368. /**
  60369. * Returns the string "HemisphericParticleEmitter"
  60370. * @returns a string containing the class name
  60371. */
  60372. HemisphericParticleEmitter.prototype.getClassName = function () {
  60373. return "HemisphericParticleEmitter";
  60374. };
  60375. /**
  60376. * Serializes the particle system to a JSON object.
  60377. * @returns the JSON object
  60378. */
  60379. HemisphericParticleEmitter.prototype.serialize = function () {
  60380. var serializationObject = {};
  60381. serializationObject.type = this.getClassName();
  60382. serializationObject.radius = this.radius;
  60383. serializationObject.radiusRange = this.radiusRange;
  60384. serializationObject.directionRandomizer = this.directionRandomizer;
  60385. return serializationObject;
  60386. };
  60387. /**
  60388. * Parse properties from a JSON object
  60389. * @param serializationObject defines the JSON object
  60390. */
  60391. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60392. this.radius = serializationObject.radius;
  60393. this.radiusRange = serializationObject.radiusRange;
  60394. this.directionRandomizer = serializationObject.directionRandomizer;
  60395. };
  60396. return HemisphericParticleEmitter;
  60397. }());
  60398. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60399. })(BABYLON || (BABYLON = {}));
  60400. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60401. var BABYLON;
  60402. (function (BABYLON) {
  60403. /**
  60404. * Particle emitter emitting particles from a point.
  60405. * It emits the particles randomly between 2 given directions.
  60406. */
  60407. var PointParticleEmitter = /** @class */ (function () {
  60408. /**
  60409. * Creates a new instance PointParticleEmitter
  60410. */
  60411. function PointParticleEmitter() {
  60412. /**
  60413. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60414. */
  60415. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60416. /**
  60417. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60418. */
  60419. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60420. }
  60421. /**
  60422. * Called by the particle System when the direction is computed for the created particle.
  60423. * @param worldMatrix is the world matrix of the particle system
  60424. * @param directionToUpdate is the direction vector to update with the result
  60425. * @param particle is the particle we are computed the direction for
  60426. */
  60427. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60428. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60429. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60430. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60431. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60432. };
  60433. /**
  60434. * Called by the particle System when the position is computed for the created particle.
  60435. * @param worldMatrix is the world matrix of the particle system
  60436. * @param positionToUpdate is the position vector to update with the result
  60437. * @param particle is the particle we are computed the position for
  60438. */
  60439. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60440. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60441. };
  60442. /**
  60443. * Clones the current emitter and returns a copy of it
  60444. * @returns the new emitter
  60445. */
  60446. PointParticleEmitter.prototype.clone = function () {
  60447. var newOne = new PointParticleEmitter();
  60448. BABYLON.Tools.DeepCopy(this, newOne);
  60449. return newOne;
  60450. };
  60451. /**
  60452. * Called by the GPUParticleSystem to setup the update shader
  60453. * @param effect defines the update shader
  60454. */
  60455. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60456. effect.setVector3("direction1", this.direction1);
  60457. effect.setVector3("direction2", this.direction2);
  60458. };
  60459. /**
  60460. * Returns a string to use to update the GPU particles update shader
  60461. * @returns a string containng the defines string
  60462. */
  60463. PointParticleEmitter.prototype.getEffectDefines = function () {
  60464. return "#define POINTEMITTER";
  60465. };
  60466. /**
  60467. * Returns the string "PointParticleEmitter"
  60468. * @returns a string containing the class name
  60469. */
  60470. PointParticleEmitter.prototype.getClassName = function () {
  60471. return "PointParticleEmitter";
  60472. };
  60473. /**
  60474. * Serializes the particle system to a JSON object.
  60475. * @returns the JSON object
  60476. */
  60477. PointParticleEmitter.prototype.serialize = function () {
  60478. var serializationObject = {};
  60479. serializationObject.type = this.getClassName();
  60480. serializationObject.direction1 = this.direction1.asArray();
  60481. serializationObject.direction2 = this.direction2.asArray();
  60482. return serializationObject;
  60483. };
  60484. /**
  60485. * Parse properties from a JSON object
  60486. * @param serializationObject defines the JSON object
  60487. */
  60488. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60489. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60490. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60491. };
  60492. return PointParticleEmitter;
  60493. }());
  60494. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60495. })(BABYLON || (BABYLON = {}));
  60496. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60497. var BABYLON;
  60498. (function (BABYLON) {
  60499. // Adds the parsers to the scene parsers.
  60500. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60501. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60502. if (!individualParser) {
  60503. return;
  60504. }
  60505. // Particles Systems
  60506. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60507. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60508. var parsedParticleSystem = parsedData.particleSystems[index];
  60509. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60510. }
  60511. }
  60512. });
  60513. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60514. if (parsedParticleSystem.activeParticleCount) {
  60515. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60516. return ps;
  60517. }
  60518. else {
  60519. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60520. return ps;
  60521. }
  60522. });
  60523. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60524. if (uniformsNames === void 0) { uniformsNames = []; }
  60525. if (samplers === void 0) { samplers = []; }
  60526. if (defines === void 0) { defines = ""; }
  60527. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60528. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60529. if (defines.indexOf(" BILLBOARD") === -1) {
  60530. defines += "\n#define BILLBOARD\n";
  60531. }
  60532. if (samplers.indexOf("diffuseSampler") === -1) {
  60533. samplers.push("diffuseSampler");
  60534. }
  60535. return this.createEffect({
  60536. vertex: "particles",
  60537. fragmentElement: fragmentName
  60538. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60539. };
  60540. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60541. var results = new Array();
  60542. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60543. var particleSystem = this.getScene().particleSystems[index];
  60544. if (particleSystem.emitter === this) {
  60545. results.push(particleSystem);
  60546. }
  60547. }
  60548. return results;
  60549. };
  60550. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60551. var results = new Array();
  60552. var descendants = this.getDescendants();
  60553. descendants.push(this);
  60554. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60555. var particleSystem = this.getScene().particleSystems[index];
  60556. var emitter = particleSystem.emitter;
  60557. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60558. results.push(particleSystem);
  60559. }
  60560. }
  60561. return results;
  60562. };
  60563. })(BABYLON || (BABYLON = {}));
  60564. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60565. var BABYLON;
  60566. (function (BABYLON) {
  60567. /**
  60568. * Type of sub emitter
  60569. */
  60570. var SubEmitterType;
  60571. (function (SubEmitterType) {
  60572. /**
  60573. * Attached to the particle over it's lifetime
  60574. */
  60575. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60576. /**
  60577. * Created when the particle dies
  60578. */
  60579. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60580. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60581. /**
  60582. * Sub emitter class used to emit particles from an existing particle
  60583. */
  60584. var SubEmitter = /** @class */ (function () {
  60585. /**
  60586. * Creates a sub emitter
  60587. * @param particleSystem the particle system to be used by the sub emitter
  60588. */
  60589. function SubEmitter(
  60590. /**
  60591. * the particle system to be used by the sub emitter
  60592. */
  60593. particleSystem) {
  60594. this.particleSystem = particleSystem;
  60595. /**
  60596. * Type of the submitter (Default: END)
  60597. */
  60598. this.type = SubEmitterType.END;
  60599. /**
  60600. * 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)
  60601. * Note: This only is supported when using an emitter of type Mesh
  60602. */
  60603. this.inheritDirection = false;
  60604. /**
  60605. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60606. */
  60607. this.inheritedVelocityAmount = 0;
  60608. }
  60609. /**
  60610. * Clones the sub emitter
  60611. * @returns the cloned sub emitter
  60612. */
  60613. SubEmitter.prototype.clone = function () {
  60614. // Clone particle system
  60615. var emitter = this.particleSystem.emitter;
  60616. if (!emitter) {
  60617. emitter = new BABYLON.Vector3();
  60618. }
  60619. else if (emitter instanceof BABYLON.Vector3) {
  60620. emitter = emitter.clone();
  60621. }
  60622. else if (emitter instanceof BABYLON.AbstractMesh) {
  60623. emitter = new BABYLON.Mesh("", emitter.getScene());
  60624. emitter.isVisible = false;
  60625. }
  60626. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60627. // Clone properties
  60628. clone.type = this.type;
  60629. clone.inheritDirection = this.inheritDirection;
  60630. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60631. clone.particleSystem._disposeEmitterOnDispose = true;
  60632. clone.particleSystem.disposeOnStop = true;
  60633. return clone;
  60634. };
  60635. /**
  60636. * Serialize current object to a JSON object
  60637. * @returns the serialized object
  60638. */
  60639. SubEmitter.prototype.serialize = function () {
  60640. var serializationObject = {};
  60641. serializationObject.type = this.type;
  60642. serializationObject.inheritDirection = this.inheritDirection;
  60643. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60644. serializationObject.particleSystem = this.particleSystem.serialize();
  60645. return serializationObject;
  60646. };
  60647. /**
  60648. * Creates a new SubEmitter from a serialized JSON version
  60649. * @param serializationObject defines the JSON object to read from
  60650. * @param scene defines the hosting scene
  60651. * @param rootUrl defines the rootUrl for data loading
  60652. * @returns a new SubEmitter
  60653. */
  60654. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  60655. var system = serializationObject.particleSystem;
  60656. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  60657. subEmitter.type = serializationObject.type;
  60658. subEmitter.inheritDirection = serializationObject.inheritDirection;
  60659. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  60660. subEmitter.particleSystem._isSubEmitter = true;
  60661. return subEmitter;
  60662. };
  60663. /** Release associated resources */
  60664. SubEmitter.prototype.dispose = function () {
  60665. this.particleSystem.dispose();
  60666. };
  60667. return SubEmitter;
  60668. }());
  60669. BABYLON.SubEmitter = SubEmitter;
  60670. })(BABYLON || (BABYLON = {}));
  60671. //# sourceMappingURL=babylon.subEmitter.js.map
  60672. var BABYLON;
  60673. (function (BABYLON) {
  60674. var ShaderMaterial = /** @class */ (function (_super) {
  60675. __extends(ShaderMaterial, _super);
  60676. function ShaderMaterial(name, scene, shaderPath, options) {
  60677. var _this = _super.call(this, name, scene) || this;
  60678. _this._textures = {};
  60679. _this._textureArrays = {};
  60680. _this._floats = {};
  60681. _this._ints = {};
  60682. _this._floatsArrays = {};
  60683. _this._colors3 = {};
  60684. _this._colors3Arrays = {};
  60685. _this._colors4 = {};
  60686. _this._vectors2 = {};
  60687. _this._vectors3 = {};
  60688. _this._vectors4 = {};
  60689. _this._matrices = {};
  60690. _this._matrices3x3 = {};
  60691. _this._matrices2x2 = {};
  60692. _this._vectors2Arrays = {};
  60693. _this._vectors3Arrays = {};
  60694. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60695. _this._shaderPath = shaderPath;
  60696. options.needAlphaBlending = options.needAlphaBlending || false;
  60697. options.needAlphaTesting = options.needAlphaTesting || false;
  60698. options.attributes = options.attributes || ["position", "normal", "uv"];
  60699. options.uniforms = options.uniforms || ["worldViewProjection"];
  60700. options.uniformBuffers = options.uniformBuffers || [];
  60701. options.samplers = options.samplers || [];
  60702. options.defines = options.defines || [];
  60703. _this._options = options;
  60704. return _this;
  60705. }
  60706. ShaderMaterial.prototype.getClassName = function () {
  60707. return "ShaderMaterial";
  60708. };
  60709. ShaderMaterial.prototype.needAlphaBlending = function () {
  60710. return this._options.needAlphaBlending;
  60711. };
  60712. ShaderMaterial.prototype.needAlphaTesting = function () {
  60713. return this._options.needAlphaTesting;
  60714. };
  60715. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60716. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60717. this._options.uniforms.push(uniformName);
  60718. }
  60719. };
  60720. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60721. if (this._options.samplers.indexOf(name) === -1) {
  60722. this._options.samplers.push(name);
  60723. }
  60724. this._textures[name] = texture;
  60725. return this;
  60726. };
  60727. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60728. if (this._options.samplers.indexOf(name) === -1) {
  60729. this._options.samplers.push(name);
  60730. }
  60731. this._checkUniform(name);
  60732. this._textureArrays[name] = textures;
  60733. return this;
  60734. };
  60735. ShaderMaterial.prototype.setFloat = function (name, value) {
  60736. this._checkUniform(name);
  60737. this._floats[name] = value;
  60738. return this;
  60739. };
  60740. ShaderMaterial.prototype.setInt = function (name, value) {
  60741. this._checkUniform(name);
  60742. this._ints[name] = value;
  60743. return this;
  60744. };
  60745. ShaderMaterial.prototype.setFloats = function (name, value) {
  60746. this._checkUniform(name);
  60747. this._floatsArrays[name] = value;
  60748. return this;
  60749. };
  60750. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60751. this._checkUniform(name);
  60752. this._colors3[name] = value;
  60753. return this;
  60754. };
  60755. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60756. this._checkUniform(name);
  60757. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60758. color.toArray(arr, arr.length);
  60759. return arr;
  60760. }, []);
  60761. return this;
  60762. };
  60763. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60764. this._checkUniform(name);
  60765. this._colors4[name] = value;
  60766. return this;
  60767. };
  60768. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60769. this._checkUniform(name);
  60770. this._vectors2[name] = value;
  60771. return this;
  60772. };
  60773. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60774. this._checkUniform(name);
  60775. this._vectors3[name] = value;
  60776. return this;
  60777. };
  60778. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60779. this._checkUniform(name);
  60780. this._vectors4[name] = value;
  60781. return this;
  60782. };
  60783. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60784. this._checkUniform(name);
  60785. this._matrices[name] = value;
  60786. return this;
  60787. };
  60788. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60789. this._checkUniform(name);
  60790. this._matrices3x3[name] = value;
  60791. return this;
  60792. };
  60793. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60794. this._checkUniform(name);
  60795. this._matrices2x2[name] = value;
  60796. return this;
  60797. };
  60798. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60799. this._checkUniform(name);
  60800. this._vectors2Arrays[name] = value;
  60801. return this;
  60802. };
  60803. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60804. this._checkUniform(name);
  60805. this._vectors3Arrays[name] = value;
  60806. return this;
  60807. };
  60808. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60809. if (!mesh) {
  60810. return true;
  60811. }
  60812. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60813. return false;
  60814. }
  60815. return false;
  60816. };
  60817. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60818. var scene = this.getScene();
  60819. var engine = scene.getEngine();
  60820. if (!this.checkReadyOnEveryCall) {
  60821. if (this._renderId === scene.getRenderId()) {
  60822. if (this._checkCache(scene, mesh, useInstances)) {
  60823. return true;
  60824. }
  60825. }
  60826. }
  60827. // Instances
  60828. var defines = [];
  60829. var attribs = [];
  60830. var fallbacks = new BABYLON.EffectFallbacks();
  60831. if (useInstances) {
  60832. defines.push("#define INSTANCES");
  60833. }
  60834. for (var index = 0; index < this._options.defines.length; index++) {
  60835. defines.push(this._options.defines[index]);
  60836. }
  60837. for (var index = 0; index < this._options.attributes.length; index++) {
  60838. attribs.push(this._options.attributes[index]);
  60839. }
  60840. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60841. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60842. defines.push("#define VERTEXCOLOR");
  60843. }
  60844. // Bones
  60845. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60848. if (mesh.numBoneInfluencers > 4) {
  60849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60851. }
  60852. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60853. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60854. fallbacks.addCPUSkinningFallback(0, mesh);
  60855. if (this._options.uniforms.indexOf("mBones") === -1) {
  60856. this._options.uniforms.push("mBones");
  60857. }
  60858. }
  60859. else {
  60860. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60861. }
  60862. // Textures
  60863. for (var name in this._textures) {
  60864. if (!this._textures[name].isReady()) {
  60865. return false;
  60866. }
  60867. }
  60868. // Alpha test
  60869. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60870. defines.push("#define ALPHATEST");
  60871. }
  60872. var previousEffect = this._effect;
  60873. var join = defines.join("\n");
  60874. this._effect = engine.createEffect(this._shaderPath, {
  60875. attributes: attribs,
  60876. uniformsNames: this._options.uniforms,
  60877. uniformBuffersNames: this._options.uniformBuffers,
  60878. samplers: this._options.samplers,
  60879. defines: join,
  60880. fallbacks: fallbacks,
  60881. onCompiled: this.onCompiled,
  60882. onError: this.onError
  60883. }, engine);
  60884. if (!this._effect.isReady()) {
  60885. return false;
  60886. }
  60887. if (previousEffect !== this._effect) {
  60888. scene.resetCachedMaterial();
  60889. }
  60890. this._renderId = scene.getRenderId();
  60891. return true;
  60892. };
  60893. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60894. var scene = this.getScene();
  60895. if (!this._effect) {
  60896. return;
  60897. }
  60898. if (this._options.uniforms.indexOf("world") !== -1) {
  60899. this._effect.setMatrix("world", world);
  60900. }
  60901. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60902. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60903. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60904. }
  60905. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60906. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60907. }
  60908. };
  60909. ShaderMaterial.prototype.bind = function (world, mesh) {
  60910. // Std values
  60911. this.bindOnlyWorldMatrix(world);
  60912. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60913. if (this._options.uniforms.indexOf("view") !== -1) {
  60914. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60915. }
  60916. if (this._options.uniforms.indexOf("projection") !== -1) {
  60917. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60918. }
  60919. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60920. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60921. }
  60922. // Bones
  60923. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60924. var name;
  60925. // Texture
  60926. for (name in this._textures) {
  60927. this._effect.setTexture(name, this._textures[name]);
  60928. }
  60929. // Texture arrays
  60930. for (name in this._textureArrays) {
  60931. this._effect.setTextureArray(name, this._textureArrays[name]);
  60932. }
  60933. // Int
  60934. for (name in this._ints) {
  60935. this._effect.setInt(name, this._ints[name]);
  60936. }
  60937. // Float
  60938. for (name in this._floats) {
  60939. this._effect.setFloat(name, this._floats[name]);
  60940. }
  60941. // Floats
  60942. for (name in this._floatsArrays) {
  60943. this._effect.setArray(name, this._floatsArrays[name]);
  60944. }
  60945. // Color3
  60946. for (name in this._colors3) {
  60947. this._effect.setColor3(name, this._colors3[name]);
  60948. }
  60949. for (name in this._colors3Arrays) {
  60950. this._effect.setArray3(name, this._colors3Arrays[name]);
  60951. }
  60952. // Color4
  60953. for (name in this._colors4) {
  60954. var color = this._colors4[name];
  60955. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60956. }
  60957. // Vector2
  60958. for (name in this._vectors2) {
  60959. this._effect.setVector2(name, this._vectors2[name]);
  60960. }
  60961. // Vector3
  60962. for (name in this._vectors3) {
  60963. this._effect.setVector3(name, this._vectors3[name]);
  60964. }
  60965. // Vector4
  60966. for (name in this._vectors4) {
  60967. this._effect.setVector4(name, this._vectors4[name]);
  60968. }
  60969. // Matrix
  60970. for (name in this._matrices) {
  60971. this._effect.setMatrix(name, this._matrices[name]);
  60972. }
  60973. // Matrix 3x3
  60974. for (name in this._matrices3x3) {
  60975. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60976. }
  60977. // Matrix 2x2
  60978. for (name in this._matrices2x2) {
  60979. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60980. }
  60981. // Vector2Array
  60982. for (name in this._vectors2Arrays) {
  60983. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60984. }
  60985. // Vector3Array
  60986. for (name in this._vectors3Arrays) {
  60987. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60988. }
  60989. }
  60990. this._afterBind(mesh);
  60991. };
  60992. ShaderMaterial.prototype.getActiveTextures = function () {
  60993. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60994. for (var name in this._textures) {
  60995. activeTextures.push(this._textures[name]);
  60996. }
  60997. for (var name in this._textureArrays) {
  60998. var array = this._textureArrays[name];
  60999. for (var index = 0; index < array.length; index++) {
  61000. activeTextures.push(array[index]);
  61001. }
  61002. }
  61003. return activeTextures;
  61004. };
  61005. ShaderMaterial.prototype.hasTexture = function (texture) {
  61006. if (_super.prototype.hasTexture.call(this, texture)) {
  61007. return true;
  61008. }
  61009. for (var name in this._textures) {
  61010. if (this._textures[name] === texture) {
  61011. return true;
  61012. }
  61013. }
  61014. for (var name in this._textureArrays) {
  61015. var array = this._textureArrays[name];
  61016. for (var index = 0; index < array.length; index++) {
  61017. if (array[index] === texture) {
  61018. return true;
  61019. }
  61020. }
  61021. }
  61022. return false;
  61023. };
  61024. ShaderMaterial.prototype.clone = function (name) {
  61025. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  61026. return newShaderMaterial;
  61027. };
  61028. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61029. if (forceDisposeTextures) {
  61030. var name;
  61031. for (name in this._textures) {
  61032. this._textures[name].dispose();
  61033. }
  61034. for (name in this._textureArrays) {
  61035. var array = this._textureArrays[name];
  61036. for (var index = 0; index < array.length; index++) {
  61037. array[index].dispose();
  61038. }
  61039. }
  61040. }
  61041. this._textures = {};
  61042. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61043. };
  61044. ShaderMaterial.prototype.serialize = function () {
  61045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61046. serializationObject.customType = "BABYLON.ShaderMaterial";
  61047. serializationObject.options = this._options;
  61048. serializationObject.shaderPath = this._shaderPath;
  61049. var name;
  61050. // Texture
  61051. serializationObject.textures = {};
  61052. for (name in this._textures) {
  61053. serializationObject.textures[name] = this._textures[name].serialize();
  61054. }
  61055. // Texture arrays
  61056. serializationObject.textureArrays = {};
  61057. for (name in this._textureArrays) {
  61058. serializationObject.textureArrays[name] = [];
  61059. var array = this._textureArrays[name];
  61060. for (var index = 0; index < array.length; index++) {
  61061. serializationObject.textureArrays[name].push(array[index].serialize());
  61062. }
  61063. }
  61064. // Float
  61065. serializationObject.floats = {};
  61066. for (name in this._floats) {
  61067. serializationObject.floats[name] = this._floats[name];
  61068. }
  61069. // Float s
  61070. serializationObject.FloatArrays = {};
  61071. for (name in this._floatsArrays) {
  61072. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  61073. }
  61074. // Color3
  61075. serializationObject.colors3 = {};
  61076. for (name in this._colors3) {
  61077. serializationObject.colors3[name] = this._colors3[name].asArray();
  61078. }
  61079. // Color3 array
  61080. serializationObject.colors3Arrays = {};
  61081. for (name in this._colors3Arrays) {
  61082. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  61083. }
  61084. // Color4
  61085. serializationObject.colors4 = {};
  61086. for (name in this._colors4) {
  61087. serializationObject.colors4[name] = this._colors4[name].asArray();
  61088. }
  61089. // Vector2
  61090. serializationObject.vectors2 = {};
  61091. for (name in this._vectors2) {
  61092. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  61093. }
  61094. // Vector3
  61095. serializationObject.vectors3 = {};
  61096. for (name in this._vectors3) {
  61097. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  61098. }
  61099. // Vector4
  61100. serializationObject.vectors4 = {};
  61101. for (name in this._vectors4) {
  61102. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  61103. }
  61104. // Matrix
  61105. serializationObject.matrices = {};
  61106. for (name in this._matrices) {
  61107. serializationObject.matrices[name] = this._matrices[name].asArray();
  61108. }
  61109. // Matrix 3x3
  61110. serializationObject.matrices3x3 = {};
  61111. for (name in this._matrices3x3) {
  61112. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  61113. }
  61114. // Matrix 2x2
  61115. serializationObject.matrices2x2 = {};
  61116. for (name in this._matrices2x2) {
  61117. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  61118. }
  61119. // Vector2Array
  61120. serializationObject.vectors2Arrays = {};
  61121. for (name in this._vectors2Arrays) {
  61122. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  61123. }
  61124. // Vector3Array
  61125. serializationObject.vectors3Arrays = {};
  61126. for (name in this._vectors3Arrays) {
  61127. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  61128. }
  61129. return serializationObject;
  61130. };
  61131. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  61132. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  61133. var name;
  61134. // Texture
  61135. for (name in source.textures) {
  61136. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  61137. }
  61138. // Texture arrays
  61139. for (name in source.textureArrays) {
  61140. var array = source.textureArrays[name];
  61141. var textureArray = new Array();
  61142. for (var index = 0; index < array.length; index++) {
  61143. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  61144. }
  61145. material.setTextureArray(name, textureArray);
  61146. }
  61147. // Float
  61148. for (name in source.floats) {
  61149. material.setFloat(name, source.floats[name]);
  61150. }
  61151. // Float s
  61152. for (name in source.floatsArrays) {
  61153. material.setFloats(name, source.floatsArrays[name]);
  61154. }
  61155. // Color3
  61156. for (name in source.colors3) {
  61157. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  61158. }
  61159. // Color3 arrays
  61160. for (name in source.colors3Arrays) {
  61161. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  61162. if (i % 3 === 0) {
  61163. arr.push([num]);
  61164. }
  61165. else {
  61166. arr[arr.length - 1].push(num);
  61167. }
  61168. return arr;
  61169. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  61170. material.setColor3Array(name, colors);
  61171. }
  61172. // Color4
  61173. for (name in source.colors4) {
  61174. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  61175. }
  61176. // Vector2
  61177. for (name in source.vectors2) {
  61178. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  61179. }
  61180. // Vector3
  61181. for (name in source.vectors3) {
  61182. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  61183. }
  61184. // Vector4
  61185. for (name in source.vectors4) {
  61186. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  61187. }
  61188. // Matrix
  61189. for (name in source.matrices) {
  61190. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  61191. }
  61192. // Matrix 3x3
  61193. for (name in source.matrices3x3) {
  61194. material.setMatrix3x3(name, source.matrices3x3[name]);
  61195. }
  61196. // Matrix 2x2
  61197. for (name in source.matrices2x2) {
  61198. material.setMatrix2x2(name, source.matrices2x2[name]);
  61199. }
  61200. // Vector2Array
  61201. for (name in source.vectors2Arrays) {
  61202. material.setArray2(name, source.vectors2Arrays[name]);
  61203. }
  61204. // Vector3Array
  61205. for (name in source.vectors3Arrays) {
  61206. material.setArray3(name, source.vectors3Arrays[name]);
  61207. }
  61208. return material;
  61209. };
  61210. return ShaderMaterial;
  61211. }(BABYLON.Material));
  61212. BABYLON.ShaderMaterial = ShaderMaterial;
  61213. })(BABYLON || (BABYLON = {}));
  61214. //# sourceMappingURL=babylon.shaderMaterial.js.map
  61215. var BABYLON;
  61216. (function (BABYLON) {
  61217. var GroundMesh = /** @class */ (function (_super) {
  61218. __extends(GroundMesh, _super);
  61219. function GroundMesh(name, scene) {
  61220. var _this = _super.call(this, name, scene) || this;
  61221. _this.generateOctree = false;
  61222. return _this;
  61223. }
  61224. GroundMesh.prototype.getClassName = function () {
  61225. return "GroundMesh";
  61226. };
  61227. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  61228. get: function () {
  61229. return Math.min(this._subdivisionsX, this._subdivisionsY);
  61230. },
  61231. enumerable: true,
  61232. configurable: true
  61233. });
  61234. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  61235. get: function () {
  61236. return this._subdivisionsX;
  61237. },
  61238. enumerable: true,
  61239. configurable: true
  61240. });
  61241. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  61242. get: function () {
  61243. return this._subdivisionsY;
  61244. },
  61245. enumerable: true,
  61246. configurable: true
  61247. });
  61248. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  61249. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  61250. this._subdivisionsX = chunksCount;
  61251. this._subdivisionsY = chunksCount;
  61252. this.subdivide(chunksCount);
  61253. // Call the octree system optimization if it is defined.
  61254. var thisAsAny = this;
  61255. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  61256. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  61257. }
  61258. };
  61259. /**
  61260. * Returns a height (y) value in the Worl system :
  61261. * the ground altitude at the coordinates (x, z) expressed in the World system.
  61262. * Returns the ground y position if (x, z) are outside the ground surface.
  61263. */
  61264. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  61265. var world = this.getWorldMatrix();
  61266. var invMat = BABYLON.Tmp.Matrix[5];
  61267. world.invertToRef(invMat);
  61268. var tmpVect = BABYLON.Tmp.Vector3[8];
  61269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  61270. x = tmpVect.x;
  61271. z = tmpVect.z;
  61272. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61273. return this.position.y;
  61274. }
  61275. if (!this._heightQuads || this._heightQuads.length == 0) {
  61276. this._initHeightQuads();
  61277. this._computeHeightQuads();
  61278. }
  61279. var facet = this._getFacetAt(x, z);
  61280. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  61281. // return y in the World system
  61282. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  61283. return tmpVect.y;
  61284. };
  61285. /**
  61286. * Returns a normalized vector (Vector3) orthogonal to the ground
  61287. * at the ground coordinates (x, z) expressed in the World system.
  61288. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  61289. */
  61290. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  61291. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  61292. this.getNormalAtCoordinatesToRef(x, z, normal);
  61293. return normal;
  61294. };
  61295. /**
  61296. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  61297. * at the ground coordinates (x, z) expressed in the World system.
  61298. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  61299. * Returns the GroundMesh.
  61300. */
  61301. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  61302. var world = this.getWorldMatrix();
  61303. var tmpMat = BABYLON.Tmp.Matrix[5];
  61304. world.invertToRef(tmpMat);
  61305. var tmpVect = BABYLON.Tmp.Vector3[8];
  61306. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  61307. x = tmpVect.x;
  61308. z = tmpVect.z;
  61309. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  61310. return this;
  61311. }
  61312. if (!this._heightQuads || this._heightQuads.length == 0) {
  61313. this._initHeightQuads();
  61314. this._computeHeightQuads();
  61315. }
  61316. var facet = this._getFacetAt(x, z);
  61317. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  61318. return this;
  61319. };
  61320. /**
  61321. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  61322. * if the ground has been updated.
  61323. * This can be used in the render loop.
  61324. * Returns the GroundMesh.
  61325. */
  61326. GroundMesh.prototype.updateCoordinateHeights = function () {
  61327. if (!this._heightQuads || this._heightQuads.length == 0) {
  61328. this._initHeightQuads();
  61329. }
  61330. this._computeHeightQuads();
  61331. return this;
  61332. };
  61333. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  61334. GroundMesh.prototype._getFacetAt = function (x, z) {
  61335. // retrieve col and row from x, z coordinates in the ground local system
  61336. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  61337. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  61338. var quad = this._heightQuads[row * this._subdivisionsX + col];
  61339. var facet;
  61340. if (z < quad.slope.x * x + quad.slope.y) {
  61341. facet = quad.facet1;
  61342. }
  61343. else {
  61344. facet = quad.facet2;
  61345. }
  61346. return facet;
  61347. };
  61348. // Creates and populates the heightMap array with "facet" elements :
  61349. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  61350. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61351. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61352. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61353. // Returns the GroundMesh.
  61354. GroundMesh.prototype._initHeightQuads = function () {
  61355. var subdivisionsX = this._subdivisionsX;
  61356. var subdivisionsY = this._subdivisionsY;
  61357. this._heightQuads = new Array();
  61358. for (var row = 0; row < subdivisionsY; row++) {
  61359. for (var col = 0; col < subdivisionsX; col++) {
  61360. 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) };
  61361. this._heightQuads[row * subdivisionsX + col] = quad;
  61362. }
  61363. }
  61364. return this;
  61365. };
  61366. // Compute each quad element values and update the the heightMap array :
  61367. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61368. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61369. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61370. // Returns the GroundMesh.
  61371. GroundMesh.prototype._computeHeightQuads = function () {
  61372. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61373. if (!positions) {
  61374. return this;
  61375. }
  61376. var v1 = BABYLON.Tmp.Vector3[3];
  61377. var v2 = BABYLON.Tmp.Vector3[2];
  61378. var v3 = BABYLON.Tmp.Vector3[1];
  61379. var v4 = BABYLON.Tmp.Vector3[0];
  61380. var v1v2 = BABYLON.Tmp.Vector3[4];
  61381. var v1v3 = BABYLON.Tmp.Vector3[5];
  61382. var v1v4 = BABYLON.Tmp.Vector3[6];
  61383. var norm1 = BABYLON.Tmp.Vector3[7];
  61384. var norm2 = BABYLON.Tmp.Vector3[8];
  61385. var i = 0;
  61386. var j = 0;
  61387. var k = 0;
  61388. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61389. var h = 0;
  61390. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61391. var d2 = 0;
  61392. var subdivisionsX = this._subdivisionsX;
  61393. var subdivisionsY = this._subdivisionsY;
  61394. for (var row = 0; row < subdivisionsY; row++) {
  61395. for (var col = 0; col < subdivisionsX; col++) {
  61396. i = col * 3;
  61397. j = row * (subdivisionsX + 1) * 3;
  61398. k = (row + 1) * (subdivisionsX + 1) * 3;
  61399. v1.x = positions[j + i];
  61400. v1.y = positions[j + i + 1];
  61401. v1.z = positions[j + i + 2];
  61402. v2.x = positions[j + i + 3];
  61403. v2.y = positions[j + i + 4];
  61404. v2.z = positions[j + i + 5];
  61405. v3.x = positions[k + i];
  61406. v3.y = positions[k + i + 1];
  61407. v3.z = positions[k + i + 2];
  61408. v4.x = positions[k + i + 3];
  61409. v4.y = positions[k + i + 4];
  61410. v4.z = positions[k + i + 5];
  61411. // 2D slope V1V4
  61412. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61413. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61414. // facet equations :
  61415. // we compute each facet normal vector
  61416. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61417. // we compute the value d by applying the equation to v1 which belongs to the plane
  61418. // then we store the facet equation in a Vector4
  61419. v2.subtractToRef(v1, v1v2);
  61420. v3.subtractToRef(v1, v1v3);
  61421. v4.subtractToRef(v1, v1v4);
  61422. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61423. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61424. norm1.normalize();
  61425. norm2.normalize();
  61426. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61427. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61428. var quad = this._heightQuads[row * subdivisionsX + col];
  61429. quad.slope.copyFromFloats(cd, h);
  61430. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61431. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61432. }
  61433. }
  61434. return this;
  61435. };
  61436. GroundMesh.prototype.serialize = function (serializationObject) {
  61437. _super.prototype.serialize.call(this, serializationObject);
  61438. serializationObject.subdivisionsX = this._subdivisionsX;
  61439. serializationObject.subdivisionsY = this._subdivisionsY;
  61440. serializationObject.minX = this._minX;
  61441. serializationObject.maxX = this._maxX;
  61442. serializationObject.minZ = this._minZ;
  61443. serializationObject.maxZ = this._maxZ;
  61444. serializationObject.width = this._width;
  61445. serializationObject.height = this._height;
  61446. };
  61447. GroundMesh.Parse = function (parsedMesh, scene) {
  61448. var result = new GroundMesh(parsedMesh.name, scene);
  61449. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61450. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61451. result._minX = parsedMesh.minX;
  61452. result._maxX = parsedMesh.maxX;
  61453. result._minZ = parsedMesh.minZ;
  61454. result._maxZ = parsedMesh.maxZ;
  61455. result._width = parsedMesh.width;
  61456. result._height = parsedMesh.height;
  61457. return result;
  61458. };
  61459. return GroundMesh;
  61460. }(BABYLON.Mesh));
  61461. BABYLON.GroundMesh = GroundMesh;
  61462. })(BABYLON || (BABYLON = {}));
  61463. //# sourceMappingURL=babylon.groundMesh.js.map
  61464. var BABYLON;
  61465. (function (BABYLON) {
  61466. /**
  61467. * Creates an instance based on a source mesh.
  61468. */
  61469. var InstancedMesh = /** @class */ (function (_super) {
  61470. __extends(InstancedMesh, _super);
  61471. function InstancedMesh(name, source) {
  61472. var _this = _super.call(this, name, source.getScene()) || this;
  61473. source.instances.push(_this);
  61474. _this._sourceMesh = source;
  61475. _this.position.copyFrom(source.position);
  61476. _this.rotation.copyFrom(source.rotation);
  61477. _this.scaling.copyFrom(source.scaling);
  61478. if (source.rotationQuaternion) {
  61479. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61480. }
  61481. _this.infiniteDistance = source.infiniteDistance;
  61482. _this.setPivotMatrix(source.getPivotMatrix());
  61483. _this.refreshBoundingInfo();
  61484. _this._syncSubMeshes();
  61485. return _this;
  61486. }
  61487. /**
  61488. * Returns the string "InstancedMesh".
  61489. */
  61490. InstancedMesh.prototype.getClassName = function () {
  61491. return "InstancedMesh";
  61492. };
  61493. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61494. // Methods
  61495. get: function () {
  61496. return this._sourceMesh.receiveShadows;
  61497. },
  61498. enumerable: true,
  61499. configurable: true
  61500. });
  61501. Object.defineProperty(InstancedMesh.prototype, "material", {
  61502. get: function () {
  61503. return this._sourceMesh.material;
  61504. },
  61505. enumerable: true,
  61506. configurable: true
  61507. });
  61508. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61509. get: function () {
  61510. return this._sourceMesh.visibility;
  61511. },
  61512. enumerable: true,
  61513. configurable: true
  61514. });
  61515. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61516. get: function () {
  61517. return this._sourceMesh.skeleton;
  61518. },
  61519. enumerable: true,
  61520. configurable: true
  61521. });
  61522. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61523. get: function () {
  61524. return this._sourceMesh.renderingGroupId;
  61525. },
  61526. set: function (value) {
  61527. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61528. return;
  61529. }
  61530. //no-op with warning
  61531. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61532. },
  61533. enumerable: true,
  61534. configurable: true
  61535. });
  61536. /**
  61537. * Returns the total number of vertices (integer).
  61538. */
  61539. InstancedMesh.prototype.getTotalVertices = function () {
  61540. return this._sourceMesh.getTotalVertices();
  61541. };
  61542. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61543. get: function () {
  61544. return this._sourceMesh;
  61545. },
  61546. enumerable: true,
  61547. configurable: true
  61548. });
  61549. /**
  61550. * Is this node ready to be used/rendered
  61551. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61552. * @return {boolean} is it ready
  61553. */
  61554. InstancedMesh.prototype.isReady = function (completeCheck) {
  61555. if (completeCheck === void 0) { completeCheck = false; }
  61556. return this._sourceMesh.isReady(completeCheck, true);
  61557. };
  61558. /**
  61559. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61560. */
  61561. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61562. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61563. };
  61564. /**
  61565. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61566. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61567. * The `data` are either a numeric array either a Float32Array.
  61568. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61569. * 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).
  61570. * Note that a new underlying VertexBuffer object is created each call.
  61571. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61572. *
  61573. * Possible `kind` values :
  61574. * - BABYLON.VertexBuffer.PositionKind
  61575. * - BABYLON.VertexBuffer.UVKind
  61576. * - BABYLON.VertexBuffer.UV2Kind
  61577. * - BABYLON.VertexBuffer.UV3Kind
  61578. * - BABYLON.VertexBuffer.UV4Kind
  61579. * - BABYLON.VertexBuffer.UV5Kind
  61580. * - BABYLON.VertexBuffer.UV6Kind
  61581. * - BABYLON.VertexBuffer.ColorKind
  61582. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61583. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61584. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61585. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61586. *
  61587. * Returns the Mesh.
  61588. */
  61589. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61590. if (this.sourceMesh) {
  61591. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61592. }
  61593. return this.sourceMesh;
  61594. };
  61595. /**
  61596. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61597. * If the mesh has no geometry, it is simply returned as it is.
  61598. * The `data` are either a numeric array either a Float32Array.
  61599. * No new underlying VertexBuffer object is created.
  61600. * 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.
  61601. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61602. *
  61603. * Possible `kind` values :
  61604. * - BABYLON.VertexBuffer.PositionKind
  61605. * - BABYLON.VertexBuffer.UVKind
  61606. * - BABYLON.VertexBuffer.UV2Kind
  61607. * - BABYLON.VertexBuffer.UV3Kind
  61608. * - BABYLON.VertexBuffer.UV4Kind
  61609. * - BABYLON.VertexBuffer.UV5Kind
  61610. * - BABYLON.VertexBuffer.UV6Kind
  61611. * - BABYLON.VertexBuffer.ColorKind
  61612. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61613. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61614. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61615. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61616. *
  61617. * Returns the Mesh.
  61618. */
  61619. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61620. if (this.sourceMesh) {
  61621. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61622. }
  61623. return this.sourceMesh;
  61624. };
  61625. /**
  61626. * Sets the mesh indices.
  61627. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61628. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61629. * This method creates a new index buffer each call.
  61630. * Returns the Mesh.
  61631. */
  61632. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61633. if (totalVertices === void 0) { totalVertices = null; }
  61634. if (this.sourceMesh) {
  61635. this.sourceMesh.setIndices(indices, totalVertices);
  61636. }
  61637. return this.sourceMesh;
  61638. };
  61639. /**
  61640. * Boolean : True if the mesh owns the requested kind of data.
  61641. */
  61642. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61643. return this._sourceMesh.isVerticesDataPresent(kind);
  61644. };
  61645. /**
  61646. * Returns an array of indices (IndicesArray).
  61647. */
  61648. InstancedMesh.prototype.getIndices = function () {
  61649. return this._sourceMesh.getIndices();
  61650. };
  61651. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61652. get: function () {
  61653. return this._sourceMesh._positions;
  61654. },
  61655. enumerable: true,
  61656. configurable: true
  61657. });
  61658. /**
  61659. * Sets a new updated BoundingInfo to the mesh.
  61660. * Returns the mesh.
  61661. */
  61662. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61663. var meshBB = this._sourceMesh.getBoundingInfo();
  61664. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61665. this._updateBoundingInfo();
  61666. return this;
  61667. };
  61668. /** @hidden */
  61669. InstancedMesh.prototype._preActivate = function () {
  61670. if (this._currentLOD) {
  61671. this._currentLOD._preActivate();
  61672. }
  61673. return this;
  61674. };
  61675. /** @hidden */
  61676. InstancedMesh.prototype._activate = function (renderId) {
  61677. if (this._currentLOD) {
  61678. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61679. }
  61680. return this;
  61681. };
  61682. /**
  61683. * Returns the current associated LOD AbstractMesh.
  61684. */
  61685. InstancedMesh.prototype.getLOD = function (camera) {
  61686. if (!camera) {
  61687. return this;
  61688. }
  61689. var boundingInfo = this.getBoundingInfo();
  61690. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61691. if (this._currentLOD === this.sourceMesh) {
  61692. return this;
  61693. }
  61694. return this._currentLOD;
  61695. };
  61696. /** @hidden */
  61697. InstancedMesh.prototype._syncSubMeshes = function () {
  61698. this.releaseSubMeshes();
  61699. if (this._sourceMesh.subMeshes) {
  61700. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61701. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61702. }
  61703. }
  61704. return this;
  61705. };
  61706. /** @hidden */
  61707. InstancedMesh.prototype._generatePointsArray = function () {
  61708. return this._sourceMesh._generatePointsArray();
  61709. };
  61710. /**
  61711. * Creates a new InstancedMesh from the current mesh.
  61712. * - name (string) : the cloned mesh name
  61713. * - newParent (optional Node) : the optional Node to parent the clone to.
  61714. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61715. *
  61716. * Returns the clone.
  61717. */
  61718. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61719. var result = this._sourceMesh.createInstance(name);
  61720. // Deep copy
  61721. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61722. // Bounding info
  61723. this.refreshBoundingInfo();
  61724. // Parent
  61725. if (newParent) {
  61726. result.parent = newParent;
  61727. }
  61728. if (!doNotCloneChildren) {
  61729. // Children
  61730. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61731. var mesh = this.getScene().meshes[index];
  61732. if (mesh.parent === this) {
  61733. mesh.clone(mesh.name, result);
  61734. }
  61735. }
  61736. }
  61737. result.computeWorldMatrix(true);
  61738. return result;
  61739. };
  61740. /**
  61741. * Disposes the InstancedMesh.
  61742. * Returns nothing.
  61743. */
  61744. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61745. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61746. // Remove from mesh
  61747. var index = this._sourceMesh.instances.indexOf(this);
  61748. this._sourceMesh.instances.splice(index, 1);
  61749. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61750. };
  61751. return InstancedMesh;
  61752. }(BABYLON.AbstractMesh));
  61753. BABYLON.InstancedMesh = InstancedMesh;
  61754. })(BABYLON || (BABYLON = {}));
  61755. //# sourceMappingURL=babylon.instancedMesh.js.map
  61756. var BABYLON;
  61757. (function (BABYLON) {
  61758. var LinesMesh = /** @class */ (function (_super) {
  61759. __extends(LinesMesh, _super);
  61760. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61761. if (scene === void 0) { scene = null; }
  61762. if (parent === void 0) { parent = null; }
  61763. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61764. _this.useVertexColor = useVertexColor;
  61765. _this.useVertexAlpha = useVertexAlpha;
  61766. _this.color = new BABYLON.Color3(1, 1, 1);
  61767. _this.alpha = 1;
  61768. if (source) {
  61769. _this.color = source.color.clone();
  61770. _this.alpha = source.alpha;
  61771. _this.useVertexColor = source.useVertexColor;
  61772. _this.useVertexAlpha = source.useVertexAlpha;
  61773. }
  61774. _this._intersectionThreshold = 0.1;
  61775. var defines = [];
  61776. var options = {
  61777. attributes: [BABYLON.VertexBuffer.PositionKind],
  61778. uniforms: ["world", "viewProjection"],
  61779. needAlphaBlending: true,
  61780. defines: defines
  61781. };
  61782. if (useVertexAlpha === false) {
  61783. options.needAlphaBlending = false;
  61784. }
  61785. if (!useVertexColor) {
  61786. options.uniforms.push("color");
  61787. }
  61788. else {
  61789. options.defines.push("#define VERTEXCOLOR");
  61790. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61791. }
  61792. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61793. return _this;
  61794. }
  61795. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61796. /**
  61797. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61798. * This margin is expressed in world space coordinates, so its value may vary.
  61799. * Default value is 0.1
  61800. * @returns the intersection Threshold value.
  61801. */
  61802. get: function () {
  61803. return this._intersectionThreshold;
  61804. },
  61805. /**
  61806. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61807. * This margin is expressed in world space coordinates, so its value may vary.
  61808. * @param value the new threshold to apply
  61809. */
  61810. set: function (value) {
  61811. if (this._intersectionThreshold === value) {
  61812. return;
  61813. }
  61814. this._intersectionThreshold = value;
  61815. if (this.geometry) {
  61816. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61817. }
  61818. },
  61819. enumerable: true,
  61820. configurable: true
  61821. });
  61822. /**
  61823. * Returns the string "LineMesh"
  61824. */
  61825. LinesMesh.prototype.getClassName = function () {
  61826. return "LinesMesh";
  61827. };
  61828. Object.defineProperty(LinesMesh.prototype, "material", {
  61829. /**
  61830. * @hidden
  61831. */
  61832. get: function () {
  61833. return this._colorShader;
  61834. },
  61835. /**
  61836. * @hidden
  61837. */
  61838. set: function (value) {
  61839. // Do nothing
  61840. },
  61841. enumerable: true,
  61842. configurable: true
  61843. });
  61844. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61845. /**
  61846. * @hidden
  61847. */
  61848. get: function () {
  61849. return false;
  61850. },
  61851. enumerable: true,
  61852. configurable: true
  61853. });
  61854. LinesMesh.prototype.createInstance = function (name) {
  61855. throw new Error("LinesMeshes do not support createInstance.");
  61856. };
  61857. /** @hidden */
  61858. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61859. if (!this._geometry) {
  61860. return this;
  61861. }
  61862. // VBOs
  61863. this._geometry._bind(this._colorShader.getEffect());
  61864. // Color
  61865. if (!this.useVertexColor) {
  61866. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61867. }
  61868. return this;
  61869. };
  61870. /** @hidden */
  61871. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61872. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61873. return this;
  61874. }
  61875. var engine = this.getScene().getEngine();
  61876. // Draw order
  61877. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61878. return this;
  61879. };
  61880. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61881. this._colorShader.dispose();
  61882. _super.prototype.dispose.call(this, doNotRecurse);
  61883. };
  61884. /**
  61885. * Returns a new LineMesh object cloned from the current one.
  61886. */
  61887. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61888. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61889. };
  61890. return LinesMesh;
  61891. }(BABYLON.Mesh));
  61892. BABYLON.LinesMesh = LinesMesh;
  61893. })(BABYLON || (BABYLON = {}));
  61894. //# sourceMappingURL=babylon.linesMesh.js.map
  61895. var BABYLON;
  61896. (function (BABYLON) {
  61897. /**
  61898. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61899. * The underlying implementation relies on an associative array to ensure the best performances.
  61900. * The value can be anything including 'null' but except 'undefined'
  61901. */
  61902. var StringDictionary = /** @class */ (function () {
  61903. function StringDictionary() {
  61904. this._count = 0;
  61905. this._data = {};
  61906. }
  61907. /**
  61908. * This will clear this dictionary and copy the content from the 'source' one.
  61909. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61910. * @param source the dictionary to take the content from and copy to this dictionary
  61911. */
  61912. StringDictionary.prototype.copyFrom = function (source) {
  61913. var _this = this;
  61914. this.clear();
  61915. source.forEach(function (t, v) { return _this.add(t, v); });
  61916. };
  61917. /**
  61918. * Get a value based from its key
  61919. * @param key the given key to get the matching value from
  61920. * @return the value if found, otherwise undefined is returned
  61921. */
  61922. StringDictionary.prototype.get = function (key) {
  61923. var val = this._data[key];
  61924. if (val !== undefined) {
  61925. return val;
  61926. }
  61927. return undefined;
  61928. };
  61929. /**
  61930. * Get a value from its key or add it if it doesn't exist.
  61931. * This method will ensure you that a given key/data will be present in the dictionary.
  61932. * @param key the given key to get the matching value from
  61933. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61934. * The factory will only be invoked if there's no data for the given key.
  61935. * @return the value corresponding to the key.
  61936. */
  61937. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61938. var val = this.get(key);
  61939. if (val !== undefined) {
  61940. return val;
  61941. }
  61942. val = factory(key);
  61943. if (val) {
  61944. this.add(key, val);
  61945. }
  61946. return val;
  61947. };
  61948. /**
  61949. * Get a value from its key if present in the dictionary otherwise add it
  61950. * @param key the key to get the value from
  61951. * @param val if there's no such key/value pair in the dictionary add it with this value
  61952. * @return the value corresponding to the key
  61953. */
  61954. StringDictionary.prototype.getOrAdd = function (key, val) {
  61955. var curVal = this.get(key);
  61956. if (curVal !== undefined) {
  61957. return curVal;
  61958. }
  61959. this.add(key, val);
  61960. return val;
  61961. };
  61962. /**
  61963. * Check if there's a given key in the dictionary
  61964. * @param key the key to check for
  61965. * @return true if the key is present, false otherwise
  61966. */
  61967. StringDictionary.prototype.contains = function (key) {
  61968. return this._data[key] !== undefined;
  61969. };
  61970. /**
  61971. * Add a new key and its corresponding value
  61972. * @param key the key to add
  61973. * @param value the value corresponding to the key
  61974. * @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
  61975. */
  61976. StringDictionary.prototype.add = function (key, value) {
  61977. if (this._data[key] !== undefined) {
  61978. return false;
  61979. }
  61980. this._data[key] = value;
  61981. ++this._count;
  61982. return true;
  61983. };
  61984. StringDictionary.prototype.set = function (key, value) {
  61985. if (this._data[key] === undefined) {
  61986. return false;
  61987. }
  61988. this._data[key] = value;
  61989. return true;
  61990. };
  61991. /**
  61992. * Get the element of the given key and remove it from the dictionary
  61993. * @param key
  61994. */
  61995. StringDictionary.prototype.getAndRemove = function (key) {
  61996. var val = this.get(key);
  61997. if (val !== undefined) {
  61998. delete this._data[key];
  61999. --this._count;
  62000. return val;
  62001. }
  62002. return null;
  62003. };
  62004. /**
  62005. * Remove a key/value from the dictionary.
  62006. * @param key the key to remove
  62007. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62008. */
  62009. StringDictionary.prototype.remove = function (key) {
  62010. if (this.contains(key)) {
  62011. delete this._data[key];
  62012. --this._count;
  62013. return true;
  62014. }
  62015. return false;
  62016. };
  62017. /**
  62018. * Clear the whole content of the dictionary
  62019. */
  62020. StringDictionary.prototype.clear = function () {
  62021. this._data = {};
  62022. this._count = 0;
  62023. };
  62024. Object.defineProperty(StringDictionary.prototype, "count", {
  62025. get: function () {
  62026. return this._count;
  62027. },
  62028. enumerable: true,
  62029. configurable: true
  62030. });
  62031. /**
  62032. * Execute a callback on each key/val of the dictionary.
  62033. * Note that you can remove any element in this dictionary in the callback implementation
  62034. * @param callback the callback to execute on a given key/value pair
  62035. */
  62036. StringDictionary.prototype.forEach = function (callback) {
  62037. for (var cur in this._data) {
  62038. var val = this._data[cur];
  62039. callback(cur, val);
  62040. }
  62041. };
  62042. /**
  62043. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62044. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62045. * Note that you can remove any element in this dictionary in the callback implementation
  62046. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62047. */
  62048. StringDictionary.prototype.first = function (callback) {
  62049. for (var cur in this._data) {
  62050. var val = this._data[cur];
  62051. var res = callback(cur, val);
  62052. if (res) {
  62053. return res;
  62054. }
  62055. }
  62056. return null;
  62057. };
  62058. return StringDictionary;
  62059. }());
  62060. BABYLON.StringDictionary = StringDictionary;
  62061. })(BABYLON || (BABYLON = {}));
  62062. //# sourceMappingURL=babylon.stringDictionary.js.map
  62063. var BABYLON;
  62064. (function (BABYLON) {
  62065. var Debug;
  62066. (function (Debug) {
  62067. /**
  62068. * Class used to render a debug view of a given skeleton
  62069. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  62070. */
  62071. var SkeletonViewer = /** @class */ (function () {
  62072. /**
  62073. * Creates a new SkeletonViewer
  62074. * @param skeleton defines the skeleton to render
  62075. * @param mesh defines the mesh attached to the skeleton
  62076. * @param scene defines the hosting scene
  62077. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  62078. * @param renderingGroupId defines the rendering group id to use with the viewer
  62079. */
  62080. function SkeletonViewer(
  62081. /** defines the skeleton to render */
  62082. skeleton,
  62083. /** defines the mesh attached to the skeleton */
  62084. mesh, scene,
  62085. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  62086. autoUpdateBonesMatrices,
  62087. /** defines the rendering group id to use with the viewer */
  62088. renderingGroupId) {
  62089. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62090. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62091. this.skeleton = skeleton;
  62092. this.mesh = mesh;
  62093. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62094. this.renderingGroupId = renderingGroupId;
  62095. /** Gets or sets the color used to render the skeleton */
  62096. this.color = BABYLON.Color3.White();
  62097. this._debugLines = new Array();
  62098. this._isEnabled = false;
  62099. this._scene = scene;
  62100. this.update();
  62101. this._renderFunction = this.update.bind(this);
  62102. }
  62103. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62104. get: function () {
  62105. return this._isEnabled;
  62106. },
  62107. /** Gets or sets a boolean indicating if the viewer is enabled */
  62108. set: function (value) {
  62109. if (this._isEnabled === value) {
  62110. return;
  62111. }
  62112. this._isEnabled = value;
  62113. if (value) {
  62114. this._scene.registerBeforeRender(this._renderFunction);
  62115. }
  62116. else {
  62117. this._scene.unregisterBeforeRender(this._renderFunction);
  62118. }
  62119. },
  62120. enumerable: true,
  62121. configurable: true
  62122. });
  62123. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62124. if (x === void 0) { x = 0; }
  62125. if (y === void 0) { y = 0; }
  62126. if (z === void 0) { z = 0; }
  62127. var tmat = BABYLON.Tmp.Matrix[0];
  62128. var parentBone = bone.getParent();
  62129. tmat.copyFrom(bone.getLocalMatrix());
  62130. if (x !== 0 || y !== 0 || z !== 0) {
  62131. var tmat2 = BABYLON.Tmp.Matrix[1];
  62132. BABYLON.Matrix.IdentityToRef(tmat2);
  62133. tmat2.m[12] = x;
  62134. tmat2.m[13] = y;
  62135. tmat2.m[14] = z;
  62136. tmat2.multiplyToRef(tmat, tmat);
  62137. }
  62138. if (parentBone) {
  62139. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62140. }
  62141. tmat.multiplyToRef(meshMat, tmat);
  62142. position.x = tmat.m[12];
  62143. position.y = tmat.m[13];
  62144. position.z = tmat.m[14];
  62145. };
  62146. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62147. var len = bones.length;
  62148. var meshPos = this.mesh.position;
  62149. for (var i = 0; i < len; i++) {
  62150. var bone = bones[i];
  62151. var points = this._debugLines[i];
  62152. if (!points) {
  62153. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62154. this._debugLines[i] = points;
  62155. }
  62156. this._getBonePosition(points[0], bone, meshMat);
  62157. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62158. points[0].subtractInPlace(meshPos);
  62159. points[1].subtractInPlace(meshPos);
  62160. }
  62161. };
  62162. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62163. var len = bones.length;
  62164. var boneNum = 0;
  62165. var meshPos = this.mesh.position;
  62166. for (var i = len - 1; i >= 0; i--) {
  62167. var childBone = bones[i];
  62168. var parentBone = childBone.getParent();
  62169. if (!parentBone) {
  62170. continue;
  62171. }
  62172. var points = this._debugLines[boneNum];
  62173. if (!points) {
  62174. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62175. this._debugLines[boneNum] = points;
  62176. }
  62177. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62178. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62179. points[0].subtractInPlace(meshPos);
  62180. points[1].subtractInPlace(meshPos);
  62181. boneNum++;
  62182. }
  62183. };
  62184. /** Update the viewer to sync with current skeleton state */
  62185. SkeletonViewer.prototype.update = function () {
  62186. if (this.autoUpdateBonesMatrices) {
  62187. this.skeleton.computeAbsoluteTransforms();
  62188. }
  62189. if (this.skeleton.bones[0].length === undefined) {
  62190. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62191. }
  62192. else {
  62193. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62194. }
  62195. if (!this._debugMesh) {
  62196. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  62197. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62198. }
  62199. else {
  62200. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62201. }
  62202. this._debugMesh.position.copyFrom(this.mesh.position);
  62203. this._debugMesh.color = this.color;
  62204. };
  62205. /** Release associated resources */
  62206. SkeletonViewer.prototype.dispose = function () {
  62207. if (this._debugMesh) {
  62208. this.isEnabled = false;
  62209. this._debugMesh.dispose();
  62210. this._debugMesh = null;
  62211. }
  62212. };
  62213. return SkeletonViewer;
  62214. }());
  62215. Debug.SkeletonViewer = SkeletonViewer;
  62216. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62217. })(BABYLON || (BABYLON = {}));
  62218. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62219. /**
  62220. * Module Debug contains the (visual) components to debug a scene correctly
  62221. */
  62222. var BABYLON;
  62223. (function (BABYLON) {
  62224. var Debug;
  62225. (function (Debug) {
  62226. /**
  62227. * The Axes viewer will show 3 axes in a specific point in space
  62228. */
  62229. var AxesViewer = /** @class */ (function () {
  62230. /**
  62231. * Creates a new AxesViewer
  62232. * @param scene defines the hosting scene
  62233. * @param scaleLines defines a number used to scale line length (1 by default)
  62234. */
  62235. function AxesViewer(scene, scaleLines) {
  62236. if (scaleLines === void 0) { scaleLines = 1; }
  62237. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62238. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62239. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62240. /**
  62241. * Gets or sets a number used to scale line length
  62242. */
  62243. this.scaleLines = 1;
  62244. this.scaleLines = scaleLines;
  62245. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62246. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62247. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62248. this._xmesh.renderingGroupId = 2;
  62249. this._ymesh.renderingGroupId = 2;
  62250. this._zmesh.renderingGroupId = 2;
  62251. this._xmesh.material.checkReadyOnlyOnce = true;
  62252. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62253. this._ymesh.material.checkReadyOnlyOnce = true;
  62254. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62255. this._zmesh.material.checkReadyOnlyOnce = true;
  62256. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62257. this.scene = scene;
  62258. }
  62259. /**
  62260. * Force the viewer to update
  62261. * @param position defines the position of the viewer
  62262. * @param xaxis defines the x axis of the viewer
  62263. * @param yaxis defines the y axis of the viewer
  62264. * @param zaxis defines the z axis of the viewer
  62265. */
  62266. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62267. var scaleLines = this.scaleLines;
  62268. if (this._xmesh) {
  62269. this._xmesh.position.copyFrom(position);
  62270. }
  62271. if (this._ymesh) {
  62272. this._ymesh.position.copyFrom(position);
  62273. }
  62274. if (this._zmesh) {
  62275. this._zmesh.position.copyFrom(position);
  62276. }
  62277. var point2 = this._xline[1];
  62278. point2.x = xaxis.x * scaleLines;
  62279. point2.y = xaxis.y * scaleLines;
  62280. point2.z = xaxis.z * scaleLines;
  62281. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  62282. point2 = this._yline[1];
  62283. point2.x = yaxis.x * scaleLines;
  62284. point2.y = yaxis.y * scaleLines;
  62285. point2.z = yaxis.z * scaleLines;
  62286. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  62287. point2 = this._zline[1];
  62288. point2.x = zaxis.x * scaleLines;
  62289. point2.y = zaxis.y * scaleLines;
  62290. point2.z = zaxis.z * scaleLines;
  62291. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  62292. };
  62293. /** Releases resources */
  62294. AxesViewer.prototype.dispose = function () {
  62295. if (this._xmesh) {
  62296. this._xmesh.dispose();
  62297. }
  62298. if (this._ymesh) {
  62299. this._ymesh.dispose();
  62300. }
  62301. if (this._zmesh) {
  62302. this._zmesh.dispose();
  62303. }
  62304. this._xmesh = null;
  62305. this._ymesh = null;
  62306. this._zmesh = null;
  62307. this.scene = null;
  62308. };
  62309. return AxesViewer;
  62310. }());
  62311. Debug.AxesViewer = AxesViewer;
  62312. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62313. })(BABYLON || (BABYLON = {}));
  62314. //# sourceMappingURL=babylon.axesViewer.js.map
  62315. var BABYLON;
  62316. (function (BABYLON) {
  62317. var Debug;
  62318. (function (Debug) {
  62319. /**
  62320. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  62321. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  62322. */
  62323. var BoneAxesViewer = /** @class */ (function (_super) {
  62324. __extends(BoneAxesViewer, _super);
  62325. /**
  62326. * Creates a new BoneAxesViewer
  62327. * @param scene defines the hosting scene
  62328. * @param bone defines the target bone
  62329. * @param mesh defines the target mesh
  62330. * @param scaleLines defines a scaling factor for line length (1 by default)
  62331. */
  62332. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62333. if (scaleLines === void 0) { scaleLines = 1; }
  62334. var _this = _super.call(this, scene, scaleLines) || this;
  62335. /** Gets current position */
  62336. _this.pos = BABYLON.Vector3.Zero();
  62337. /** Gets direction of X axis */
  62338. _this.xaxis = BABYLON.Vector3.Zero();
  62339. /** Gets direction of Y axis */
  62340. _this.yaxis = BABYLON.Vector3.Zero();
  62341. /** Gets direction of Z axis */
  62342. _this.zaxis = BABYLON.Vector3.Zero();
  62343. _this.mesh = mesh;
  62344. _this.bone = bone;
  62345. return _this;
  62346. }
  62347. /**
  62348. * Force the viewer to update
  62349. */
  62350. BoneAxesViewer.prototype.update = function () {
  62351. if (!this.mesh || !this.bone) {
  62352. return;
  62353. }
  62354. var bone = this.bone;
  62355. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62356. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62357. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62358. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62359. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62360. };
  62361. /** Releases resources */
  62362. BoneAxesViewer.prototype.dispose = function () {
  62363. if (this.mesh) {
  62364. this.mesh = null;
  62365. this.bone = null;
  62366. _super.prototype.dispose.call(this);
  62367. }
  62368. };
  62369. return BoneAxesViewer;
  62370. }(Debug.AxesViewer));
  62371. Debug.BoneAxesViewer = BoneAxesViewer;
  62372. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62373. })(BABYLON || (BABYLON = {}));
  62374. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62375. var BABYLON;
  62376. (function (BABYLON) {
  62377. /**
  62378. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62379. * in order to better appreciate the issue one might have.
  62380. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62381. */
  62382. var RayHelper = /** @class */ (function () {
  62383. /**
  62384. * Instantiate a new ray helper.
  62385. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  62386. * in order to better appreciate the issue one might have.
  62387. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  62388. * @param ray Defines the ray we are currently tryin to visualize
  62389. */
  62390. function RayHelper(ray) {
  62391. this.ray = ray;
  62392. }
  62393. /**
  62394. * Helper function to create a colored helper in a scene in one line.
  62395. * @param ray Defines the ray we are currently tryin to visualize
  62396. * @param scene Defines the scene the ray is used in
  62397. * @param color Defines the color we want to see the ray in
  62398. * @returns The newly created ray helper.
  62399. */
  62400. RayHelper.CreateAndShow = function (ray, scene, color) {
  62401. var helper = new RayHelper(ray);
  62402. helper.show(scene, color);
  62403. return helper;
  62404. };
  62405. /**
  62406. * Shows the ray we are willing to debug.
  62407. * @param scene Defines the scene the ray needs to be rendered in
  62408. * @param color Defines the color the ray needs to be rendered in
  62409. */
  62410. RayHelper.prototype.show = function (scene, color) {
  62411. if (!this._renderFunction && this.ray) {
  62412. var ray = this.ray;
  62413. this._renderFunction = this._render.bind(this);
  62414. this._scene = scene;
  62415. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62416. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62417. if (this._renderFunction) {
  62418. this._scene.registerBeforeRender(this._renderFunction);
  62419. }
  62420. }
  62421. if (color && this._renderLine) {
  62422. this._renderLine.color.copyFrom(color);
  62423. }
  62424. };
  62425. /**
  62426. * Hides the ray we are debugging.
  62427. */
  62428. RayHelper.prototype.hide = function () {
  62429. if (this._renderFunction && this._scene) {
  62430. this._scene.unregisterBeforeRender(this._renderFunction);
  62431. this._scene = null;
  62432. this._renderFunction = null;
  62433. if (this._renderLine) {
  62434. this._renderLine.dispose();
  62435. this._renderLine = null;
  62436. }
  62437. this._renderPoints = [];
  62438. }
  62439. };
  62440. RayHelper.prototype._render = function () {
  62441. var ray = this.ray;
  62442. if (!ray) {
  62443. return;
  62444. }
  62445. var point = this._renderPoints[1];
  62446. var len = Math.min(ray.length, 1000000);
  62447. point.copyFrom(ray.direction);
  62448. point.scaleInPlace(len);
  62449. point.addInPlace(ray.origin);
  62450. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62451. };
  62452. /**
  62453. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  62454. * @param mesh Defines the mesh we want the helper attached to
  62455. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  62456. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  62457. * @param length Defines the length of the ray
  62458. */
  62459. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62460. this._attachedToMesh = mesh;
  62461. var ray = this.ray;
  62462. if (!ray) {
  62463. return;
  62464. }
  62465. if (!ray.direction) {
  62466. ray.direction = BABYLON.Vector3.Zero();
  62467. }
  62468. if (!ray.origin) {
  62469. ray.origin = BABYLON.Vector3.Zero();
  62470. }
  62471. if (length) {
  62472. ray.length = length;
  62473. }
  62474. if (!meshSpaceOrigin) {
  62475. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62476. }
  62477. if (!meshSpaceDirection) {
  62478. // -1 so that this will work with Mesh.lookAt
  62479. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62480. }
  62481. if (!this._meshSpaceDirection) {
  62482. this._meshSpaceDirection = meshSpaceDirection.clone();
  62483. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62484. }
  62485. else {
  62486. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62487. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62488. }
  62489. if (!this._updateToMeshFunction) {
  62490. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62491. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62492. }
  62493. this._updateToMesh();
  62494. };
  62495. /**
  62496. * Detach the ray helper from the mesh it has previously been attached to.
  62497. */
  62498. RayHelper.prototype.detachFromMesh = function () {
  62499. if (this._attachedToMesh) {
  62500. if (this._updateToMeshFunction) {
  62501. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62502. }
  62503. this._attachedToMesh = null;
  62504. this._updateToMeshFunction = null;
  62505. }
  62506. };
  62507. RayHelper.prototype._updateToMesh = function () {
  62508. var ray = this.ray;
  62509. if (!this._attachedToMesh || !ray) {
  62510. return;
  62511. }
  62512. if (this._attachedToMesh._isDisposed) {
  62513. this.detachFromMesh();
  62514. return;
  62515. }
  62516. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62517. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62518. };
  62519. /**
  62520. * Dispose the helper and release its associated resources.
  62521. */
  62522. RayHelper.prototype.dispose = function () {
  62523. this.hide();
  62524. this.detachFromMesh();
  62525. this.ray = null;
  62526. };
  62527. return RayHelper;
  62528. }());
  62529. BABYLON.RayHelper = RayHelper;
  62530. })(BABYLON || (BABYLON = {}));
  62531. //# sourceMappingURL=babylon.rayHelper.js.map
  62532. var BABYLON;
  62533. (function (BABYLON) {
  62534. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62535. get: function () {
  62536. if (!this._debugLayer) {
  62537. this._debugLayer = new DebugLayer(this);
  62538. }
  62539. return this._debugLayer;
  62540. },
  62541. enumerable: true,
  62542. configurable: true
  62543. });
  62544. /**
  62545. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62546. * what is happening in your scene
  62547. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62548. */
  62549. var DebugLayer = /** @class */ (function () {
  62550. /**
  62551. * Instantiates a new debug layer.
  62552. * The debug layer (aka Inspector) is the go to tool in order to better understand
  62553. * what is happening in your scene
  62554. * @see http://doc.babylonjs.com/features/playground_debuglayer
  62555. * @param scene Defines the scene to inspect
  62556. */
  62557. function DebugLayer(scene) {
  62558. var _this = this;
  62559. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62560. /**
  62561. * Observable triggered when a property is changed through the inspector.
  62562. */
  62563. this.onPropertyChangedObservable = new BABYLON.Observable();
  62564. this._scene = scene;
  62565. this._scene.onDisposeObservable.add(function () {
  62566. // Debug layer
  62567. if (_this._scene._debugLayer) {
  62568. _this._scene._debugLayer.hide();
  62569. }
  62570. });
  62571. }
  62572. /** Creates the inspector window. */
  62573. DebugLayer.prototype._createInspector = function (config) {
  62574. if (config === void 0) { config = {}; }
  62575. var popup = config.popup || false;
  62576. var initialTab = config.initialTab || 0;
  62577. var parentElement = config.parentElement || null;
  62578. if (!this._inspector) {
  62579. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62580. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62581. } // else nothing to do as instance is already created
  62582. };
  62583. /**
  62584. * Get if the inspector is visible or not.
  62585. * @returns true if visible otherwise, false
  62586. */
  62587. DebugLayer.prototype.isVisible = function () {
  62588. if (!this._inspector) {
  62589. return false;
  62590. }
  62591. return true;
  62592. };
  62593. /**
  62594. * Hide the inspector and close its window.
  62595. */
  62596. DebugLayer.prototype.hide = function () {
  62597. if (this._inspector) {
  62598. try {
  62599. this._inspector.dispose();
  62600. }
  62601. catch (e) {
  62602. // If the inspector has been removed directly from the inspector tool
  62603. }
  62604. this.onPropertyChangedObservable.clear();
  62605. this._inspector = null;
  62606. }
  62607. };
  62608. /**
  62609. *
  62610. * Launch the debugLayer.
  62611. *
  62612. * initialTab:
  62613. * | Value | Tab Name |
  62614. * | --- | --- |
  62615. * | 0 | Scene |
  62616. * | 1 | Console |
  62617. * | 2 | Stats |
  62618. * | 3 | Textures |
  62619. * | 4 | Mesh |
  62620. * | 5 | Light |
  62621. * | 6 | Material |
  62622. * | 7 | GLTF |
  62623. * | 8 | GUI |
  62624. * | 9 | Physics |
  62625. * | 10 | Camera |
  62626. * | 11 | Audio |
  62627. *
  62628. * @param config Define the configuration of the inspector
  62629. */
  62630. DebugLayer.prototype.show = function (config) {
  62631. if (config === void 0) { config = {}; }
  62632. if (typeof this.BJSINSPECTOR == 'undefined') {
  62633. // Load inspector and add it to the DOM
  62634. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62635. }
  62636. else {
  62637. // Otherwise creates the inspector
  62638. this._createInspector(config);
  62639. }
  62640. };
  62641. /**
  62642. * Gets the active tab
  62643. * @return the index of the active tab or -1 if the inspector is hidden
  62644. */
  62645. DebugLayer.prototype.getActiveTab = function () {
  62646. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62647. };
  62648. /**
  62649. * Define the url to get the inspector script from.
  62650. * By default it uses the babylonjs CDN.
  62651. * @ignoreNaming
  62652. */
  62653. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62654. return DebugLayer;
  62655. }());
  62656. BABYLON.DebugLayer = DebugLayer;
  62657. })(BABYLON || (BABYLON = {}));
  62658. //# sourceMappingURL=babylon.debugLayer.js.map
  62659. var BABYLON;
  62660. (function (BABYLON) {
  62661. var Debug;
  62662. (function (Debug) {
  62663. /**
  62664. * Used to show the physics impostor around the specific mesh
  62665. */
  62666. var PhysicsViewer = /** @class */ (function () {
  62667. /**
  62668. * Creates a new PhysicsViewer
  62669. * @param scene defines the hosting scene
  62670. */
  62671. function PhysicsViewer(scene) {
  62672. /** @hidden */
  62673. this._impostors = [];
  62674. /** @hidden */
  62675. this._meshes = [];
  62676. /** @hidden */
  62677. this._numMeshes = 0;
  62678. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62679. var physicEngine = this._scene.getPhysicsEngine();
  62680. if (physicEngine) {
  62681. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62682. }
  62683. }
  62684. /** @hidden */
  62685. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62686. var plugin = this._physicsEnginePlugin;
  62687. for (var i = 0; i < this._numMeshes; i++) {
  62688. var impostor = this._impostors[i];
  62689. if (!impostor) {
  62690. continue;
  62691. }
  62692. if (impostor.isDisposed) {
  62693. this.hideImpostor(this._impostors[i--]);
  62694. }
  62695. else {
  62696. var mesh = this._meshes[i];
  62697. if (mesh && plugin) {
  62698. plugin.syncMeshWithImpostor(mesh, impostor);
  62699. }
  62700. }
  62701. }
  62702. };
  62703. /**
  62704. * Renders a specified physic impostor
  62705. * @param impostor defines the impostor to render
  62706. */
  62707. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62708. if (!this._scene) {
  62709. return;
  62710. }
  62711. for (var i = 0; i < this._numMeshes; i++) {
  62712. if (this._impostors[i] == impostor) {
  62713. return;
  62714. }
  62715. }
  62716. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62717. if (debugMesh) {
  62718. this._impostors[this._numMeshes] = impostor;
  62719. this._meshes[this._numMeshes] = debugMesh;
  62720. if (this._numMeshes === 0) {
  62721. this._renderFunction = this._updateDebugMeshes.bind(this);
  62722. this._scene.registerBeforeRender(this._renderFunction);
  62723. }
  62724. this._numMeshes++;
  62725. }
  62726. };
  62727. /**
  62728. * Hides a specified physic impostor
  62729. * @param impostor defines the impostor to hide
  62730. */
  62731. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62732. if (!impostor || !this._scene) {
  62733. return;
  62734. }
  62735. var removed = false;
  62736. for (var i = 0; i < this._numMeshes; i++) {
  62737. if (this._impostors[i] == impostor) {
  62738. var mesh = this._meshes[i];
  62739. if (!mesh) {
  62740. continue;
  62741. }
  62742. this._scene.removeMesh(mesh);
  62743. mesh.dispose();
  62744. this._numMeshes--;
  62745. if (this._numMeshes > 0) {
  62746. this._meshes[i] = this._meshes[this._numMeshes];
  62747. this._impostors[i] = this._impostors[this._numMeshes];
  62748. this._meshes[this._numMeshes] = null;
  62749. this._impostors[this._numMeshes] = null;
  62750. }
  62751. else {
  62752. this._meshes[0] = null;
  62753. this._impostors[0] = null;
  62754. }
  62755. removed = true;
  62756. break;
  62757. }
  62758. }
  62759. if (removed && this._numMeshes === 0) {
  62760. this._scene.unregisterBeforeRender(this._renderFunction);
  62761. }
  62762. };
  62763. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62764. if (!this._debugMaterial) {
  62765. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62766. this._debugMaterial.wireframe = true;
  62767. }
  62768. return this._debugMaterial;
  62769. };
  62770. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62771. if (!this._debugBoxMesh) {
  62772. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62773. this._debugBoxMesh.renderingGroupId = 1;
  62774. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62775. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62776. scene.removeMesh(this._debugBoxMesh);
  62777. }
  62778. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62779. };
  62780. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62781. if (!this._debugSphereMesh) {
  62782. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62783. this._debugSphereMesh.renderingGroupId = 1;
  62784. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62785. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62786. scene.removeMesh(this._debugSphereMesh);
  62787. }
  62788. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62789. };
  62790. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62791. var mesh = null;
  62792. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62793. mesh = this._getDebugBoxMesh(scene);
  62794. impostor.getBoxSizeToRef(mesh.scaling);
  62795. }
  62796. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62797. mesh = this._getDebugSphereMesh(scene);
  62798. var radius = impostor.getRadius();
  62799. mesh.scaling.x = radius * 2;
  62800. mesh.scaling.y = radius * 2;
  62801. mesh.scaling.z = radius * 2;
  62802. }
  62803. return mesh;
  62804. };
  62805. /** Releases all resources */
  62806. PhysicsViewer.prototype.dispose = function () {
  62807. for (var i = 0; i < this._numMeshes; i++) {
  62808. this.hideImpostor(this._impostors[i]);
  62809. }
  62810. if (this._debugBoxMesh) {
  62811. this._debugBoxMesh.dispose();
  62812. }
  62813. if (this._debugSphereMesh) {
  62814. this._debugSphereMesh.dispose();
  62815. }
  62816. if (this._debugMaterial) {
  62817. this._debugMaterial.dispose();
  62818. }
  62819. this._impostors.length = 0;
  62820. this._scene = null;
  62821. this._physicsEnginePlugin = null;
  62822. };
  62823. return PhysicsViewer;
  62824. }());
  62825. Debug.PhysicsViewer = PhysicsViewer;
  62826. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62827. })(BABYLON || (BABYLON = {}));
  62828. //# sourceMappingURL=babylon.physicsViewer.js.map
  62829. var BABYLON;
  62830. (function (BABYLON) {
  62831. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62832. get: function () {
  62833. return this._forceShowBoundingBoxes || false;
  62834. },
  62835. set: function (value) {
  62836. this._forceShowBoundingBoxes = value;
  62837. // Lazyly creates a BB renderer if needed.
  62838. if (value) {
  62839. this.getBoundingBoxRenderer();
  62840. }
  62841. },
  62842. enumerable: true,
  62843. configurable: true
  62844. });
  62845. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62846. if (!this._boundingBoxRenderer) {
  62847. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62848. }
  62849. return this._boundingBoxRenderer;
  62850. };
  62851. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62852. get: function () {
  62853. return this._showBoundingBox || false;
  62854. },
  62855. set: function (value) {
  62856. this._showBoundingBox = value;
  62857. // Lazyly creates a BB renderer if needed.
  62858. if (value) {
  62859. this.getScene().getBoundingBoxRenderer();
  62860. }
  62861. },
  62862. enumerable: true,
  62863. configurable: true
  62864. });
  62865. /**
  62866. * Component responsible of rendering the bounding box of the meshes in a scene.
  62867. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  62868. */
  62869. var BoundingBoxRenderer = /** @class */ (function () {
  62870. /**
  62871. * Instantiates a new bounding box renderer in a scene.
  62872. * @param scene the scene the renderer renders in
  62873. */
  62874. function BoundingBoxRenderer(scene) {
  62875. /**
  62876. * The component name helpfull to identify the component in the list of scene components.
  62877. */
  62878. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62879. /**
  62880. * Color of the bounding box lines placed in front of an object
  62881. */
  62882. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62883. /**
  62884. * Color of the bounding box lines placed behind an object
  62885. */
  62886. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62887. /**
  62888. * Defines if the renderer should show the back lines or not
  62889. */
  62890. this.showBackLines = true;
  62891. /**
  62892. * @hidden
  62893. */
  62894. this.renderList = new BABYLON.SmartArray(32);
  62895. this._vertexBuffers = {};
  62896. this.scene = scene;
  62897. scene._addComponent(this);
  62898. }
  62899. /**
  62900. * Registers the component in a given scene
  62901. */
  62902. BoundingBoxRenderer.prototype.register = function () {
  62903. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62904. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62905. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62906. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62907. };
  62908. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62909. if (mesh.showSubMeshesBoundingBox) {
  62910. var boundingInfo = subMesh.getBoundingInfo();
  62911. if (boundingInfo !== null && boundingInfo !== undefined) {
  62912. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62913. this.renderList.push(boundingInfo.boundingBox);
  62914. }
  62915. }
  62916. };
  62917. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62918. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62919. var boundingInfo = sourceMesh.getBoundingInfo();
  62920. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62921. this.renderList.push(boundingInfo.boundingBox);
  62922. }
  62923. };
  62924. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62925. if (this._colorShader) {
  62926. return;
  62927. }
  62928. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62929. attributes: [BABYLON.VertexBuffer.PositionKind],
  62930. uniforms: ["world", "viewProjection", "color"]
  62931. });
  62932. var engine = this.scene.getEngine();
  62933. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62934. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62935. this._createIndexBuffer();
  62936. };
  62937. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62938. var engine = this.scene.getEngine();
  62939. 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]);
  62940. };
  62941. /**
  62942. * Rebuilds the elements related to this component in case of
  62943. * context lost for instance.
  62944. */
  62945. BoundingBoxRenderer.prototype.rebuild = function () {
  62946. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62947. if (vb) {
  62948. vb._rebuild();
  62949. }
  62950. this._createIndexBuffer();
  62951. };
  62952. /**
  62953. * @hidden
  62954. */
  62955. BoundingBoxRenderer.prototype.reset = function () {
  62956. this.renderList.reset();
  62957. };
  62958. /**
  62959. * Render the bounding boxes of a specific rendering group
  62960. * @param renderingGroupId defines the rendering group to render
  62961. */
  62962. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62963. if (this.renderList.length === 0) {
  62964. return;
  62965. }
  62966. this._prepareRessources();
  62967. if (!this._colorShader.isReady()) {
  62968. return;
  62969. }
  62970. var engine = this.scene.getEngine();
  62971. engine.setDepthWrite(false);
  62972. this._colorShader._preBind();
  62973. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62974. var boundingBox = this.renderList.data[boundingBoxIndex];
  62975. if (boundingBox._tag !== renderingGroupId) {
  62976. continue;
  62977. }
  62978. var min = boundingBox.minimum;
  62979. var max = boundingBox.maximum;
  62980. var diff = max.subtract(min);
  62981. var median = min.add(diff.scale(0.5));
  62982. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62983. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62984. .multiply(boundingBox.getWorldMatrix());
  62985. // VBOs
  62986. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62987. if (this.showBackLines) {
  62988. // Back
  62989. engine.setDepthFunctionToGreaterOrEqual();
  62990. this.scene.resetCachedMaterial();
  62991. this._colorShader.setColor4("color", this.backColor.toColor4());
  62992. this._colorShader.bind(worldMatrix);
  62993. // Draw order
  62994. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62995. }
  62996. // Front
  62997. engine.setDepthFunctionToLess();
  62998. this.scene.resetCachedMaterial();
  62999. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63000. this._colorShader.bind(worldMatrix);
  63001. // Draw order
  63002. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63003. }
  63004. this._colorShader.unbind();
  63005. engine.setDepthFunctionToLessOrEqual();
  63006. engine.setDepthWrite(true);
  63007. };
  63008. /**
  63009. * In case of occlusion queries, we can render the occlusion bounding box through this method
  63010. * @param mesh Define the mesh to render the occlusion bounding box for
  63011. */
  63012. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63013. this._prepareRessources();
  63014. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  63015. return;
  63016. }
  63017. var engine = this.scene.getEngine();
  63018. engine.setDepthWrite(false);
  63019. engine.setColorWrite(false);
  63020. this._colorShader._preBind();
  63021. var boundingBox = mesh._boundingInfo.boundingBox;
  63022. var min = boundingBox.minimum;
  63023. var max = boundingBox.maximum;
  63024. var diff = max.subtract(min);
  63025. var median = min.add(diff.scale(0.5));
  63026. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63027. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63028. .multiply(boundingBox.getWorldMatrix());
  63029. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63030. engine.setDepthFunctionToLess();
  63031. this.scene.resetCachedMaterial();
  63032. this._colorShader.bind(worldMatrix);
  63033. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  63034. this._colorShader.unbind();
  63035. engine.setDepthFunctionToLessOrEqual();
  63036. engine.setDepthWrite(true);
  63037. engine.setColorWrite(true);
  63038. };
  63039. /**
  63040. * Dispose and release the resources attached to this renderer.
  63041. */
  63042. BoundingBoxRenderer.prototype.dispose = function () {
  63043. if (!this._colorShader) {
  63044. return;
  63045. }
  63046. this.renderList.dispose();
  63047. this._colorShader.dispose();
  63048. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63049. if (buffer) {
  63050. buffer.dispose();
  63051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63052. }
  63053. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  63054. };
  63055. return BoundingBoxRenderer;
  63056. }());
  63057. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63058. })(BABYLON || (BABYLON = {}));
  63059. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63060. var BABYLON;
  63061. (function (BABYLON) {
  63062. BABYLON.Engine.prototype.createTransformFeedback = function () {
  63063. return this._gl.createTransformFeedback();
  63064. };
  63065. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  63066. this._gl.deleteTransformFeedback(value);
  63067. };
  63068. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  63069. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  63070. };
  63071. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  63072. if (usePoints === void 0) { usePoints = true; }
  63073. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  63074. };
  63075. BABYLON.Engine.prototype.endTransformFeedback = function () {
  63076. this._gl.endTransformFeedback();
  63077. };
  63078. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  63079. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  63080. };
  63081. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  63082. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  63083. };
  63084. })(BABYLON || (BABYLON = {}));
  63085. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  63086. var BABYLON;
  63087. (function (BABYLON) {
  63088. /**
  63089. * This represents a GPU particle system in Babylon
  63090. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  63091. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  63092. */
  63093. var GPUParticleSystem = /** @class */ (function (_super) {
  63094. __extends(GPUParticleSystem, _super);
  63095. /**
  63096. * Instantiates a GPU particle system.
  63097. * 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.
  63098. * @param name The name of the particle system
  63099. * @param options The options used to create the system
  63100. * @param scene The scene the particle system belongs to
  63101. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  63102. */
  63103. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  63104. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  63105. var _this = _super.call(this, name) || this;
  63106. /**
  63107. * The layer mask we are rendering the particles through.
  63108. */
  63109. _this.layerMask = 0x0FFFFFFF;
  63110. _this._accumulatedCount = 0;
  63111. _this._targetIndex = 0;
  63112. _this._currentRenderId = -1;
  63113. _this._started = false;
  63114. _this._stopped = false;
  63115. _this._timeDelta = 0;
  63116. _this._attributesStrideSize = 21;
  63117. _this._actualFrame = 0;
  63118. _this._rawTextureWidth = 256;
  63119. /**
  63120. * An event triggered when the system is disposed.
  63121. */
  63122. _this.onDisposeObservable = new BABYLON.Observable();
  63123. /**
  63124. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  63125. * to override the particles.
  63126. */
  63127. _this.forceDepthWrite = false;
  63128. _this._preWarmDone = false;
  63129. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63130. // Setup the default processing configuration to the scene.
  63131. _this._attachImageProcessingConfiguration(null);
  63132. _this._engine = _this._scene.getEngine();
  63133. if (!options.randomTextureSize) {
  63134. delete options.randomTextureSize;
  63135. }
  63136. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  63137. var optionsAsNumber = options;
  63138. if (isFinite(optionsAsNumber)) {
  63139. fullOptions.capacity = optionsAsNumber;
  63140. }
  63141. _this._capacity = fullOptions.capacity;
  63142. _this._activeCount = fullOptions.capacity;
  63143. _this._currentActiveCount = 0;
  63144. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  63145. _this._scene.particleSystems.push(_this);
  63146. _this._updateEffectOptions = {
  63147. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  63148. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  63149. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  63150. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  63151. uniformBuffersNames: [],
  63152. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  63153. defines: "",
  63154. fallbacks: null,
  63155. onCompiled: null,
  63156. onError: null,
  63157. indexParameters: null,
  63158. maxSimultaneousLights: 0,
  63159. transformFeedbackVaryings: []
  63160. };
  63161. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  63162. // Random data
  63163. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  63164. var d = [];
  63165. for (var i = 0; i < maxTextureSize; ++i) {
  63166. d.push(Math.random());
  63167. d.push(Math.random());
  63168. d.push(Math.random());
  63169. d.push(Math.random());
  63170. }
  63171. _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);
  63172. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63173. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63174. d = [];
  63175. for (var i = 0; i < maxTextureSize; ++i) {
  63176. d.push(Math.random());
  63177. d.push(Math.random());
  63178. d.push(Math.random());
  63179. d.push(Math.random());
  63180. }
  63181. _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);
  63182. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63183. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63184. _this._randomTextureSize = maxTextureSize;
  63185. return _this;
  63186. }
  63187. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  63188. /**
  63189. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  63190. */
  63191. get: function () {
  63192. if (!BABYLON.Engine.LastCreatedEngine) {
  63193. return false;
  63194. }
  63195. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  63196. },
  63197. enumerable: true,
  63198. configurable: true
  63199. });
  63200. /**
  63201. * Gets the maximum number of particles active at the same time.
  63202. * @returns The max number of active particles.
  63203. */
  63204. GPUParticleSystem.prototype.getCapacity = function () {
  63205. return this._capacity;
  63206. };
  63207. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  63208. /**
  63209. * Gets or set the number of active particles
  63210. */
  63211. get: function () {
  63212. return this._activeCount;
  63213. },
  63214. set: function (value) {
  63215. this._activeCount = Math.min(value, this._capacity);
  63216. },
  63217. enumerable: true,
  63218. configurable: true
  63219. });
  63220. /**
  63221. * Is this system ready to be used/rendered
  63222. * @return true if the system is ready
  63223. */
  63224. GPUParticleSystem.prototype.isReady = function () {
  63225. if (!this._updateEffect) {
  63226. this._recreateUpdateEffect();
  63227. this._recreateRenderEffect();
  63228. return false;
  63229. }
  63230. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  63231. return false;
  63232. }
  63233. return true;
  63234. };
  63235. /**
  63236. * Gets if the system has been started. (Note: this will still be true after stop is called)
  63237. * @returns True if it has been started, otherwise false.
  63238. */
  63239. GPUParticleSystem.prototype.isStarted = function () {
  63240. return this._started;
  63241. };
  63242. /**
  63243. * Starts the particle system and begins to emit
  63244. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  63245. */
  63246. GPUParticleSystem.prototype.start = function (delay) {
  63247. var _this = this;
  63248. if (delay === void 0) { delay = this.startDelay; }
  63249. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  63250. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  63251. }
  63252. if (delay) {
  63253. setTimeout(function () {
  63254. _this.start(0);
  63255. }, delay);
  63256. return;
  63257. }
  63258. this._started = true;
  63259. this._stopped = false;
  63260. this._preWarmDone = false;
  63261. // Animations
  63262. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  63263. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  63264. }
  63265. };
  63266. /**
  63267. * Stops the particle system.
  63268. */
  63269. GPUParticleSystem.prototype.stop = function () {
  63270. this._stopped = true;
  63271. };
  63272. /**
  63273. * Remove all active particles
  63274. */
  63275. GPUParticleSystem.prototype.reset = function () {
  63276. this._releaseBuffers();
  63277. this._releaseVAOs();
  63278. this._currentActiveCount = 0;
  63279. this._targetIndex = 0;
  63280. };
  63281. /**
  63282. * Returns the string "GPUParticleSystem"
  63283. * @returns a string containing the class name
  63284. */
  63285. GPUParticleSystem.prototype.getClassName = function () {
  63286. return "GPUParticleSystem";
  63287. };
  63288. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  63289. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  63290. this._releaseBuffers();
  63291. return this;
  63292. };
  63293. /**
  63294. * Adds a new color gradient
  63295. * @param gradient defines the gradient to use (between 0 and 1)
  63296. * @param color1 defines the color to affect to the specified gradient
  63297. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  63298. * @returns the current particle system
  63299. */
  63300. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  63301. if (!this._colorGradients) {
  63302. this._colorGradients = [];
  63303. }
  63304. var colorGradient = new BABYLON.ColorGradient();
  63305. colorGradient.gradient = gradient;
  63306. colorGradient.color1 = color1;
  63307. this._colorGradients.push(colorGradient);
  63308. this._colorGradients.sort(function (a, b) {
  63309. if (a.gradient < b.gradient) {
  63310. return -1;
  63311. }
  63312. else if (a.gradient > b.gradient) {
  63313. return 1;
  63314. }
  63315. return 0;
  63316. });
  63317. if (this._colorGradientsTexture) {
  63318. this._colorGradientsTexture.dispose();
  63319. this._colorGradientsTexture = null;
  63320. }
  63321. this._releaseBuffers();
  63322. return this;
  63323. };
  63324. /**
  63325. * Remove a specific color gradient
  63326. * @param gradient defines the gradient to remove
  63327. * @returns the current particle system
  63328. */
  63329. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  63330. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  63331. this._colorGradientsTexture = null;
  63332. return this;
  63333. };
  63334. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  63335. var valueGradient = new BABYLON.FactorGradient();
  63336. valueGradient.gradient = gradient;
  63337. valueGradient.factor1 = factor;
  63338. factorGradients.push(valueGradient);
  63339. factorGradients.sort(function (a, b) {
  63340. if (a.gradient < b.gradient) {
  63341. return -1;
  63342. }
  63343. else if (a.gradient > b.gradient) {
  63344. return 1;
  63345. }
  63346. return 0;
  63347. });
  63348. this._releaseBuffers();
  63349. };
  63350. /**
  63351. * Adds a new size gradient
  63352. * @param gradient defines the gradient to use (between 0 and 1)
  63353. * @param factor defines the size factor to affect to the specified gradient
  63354. * @returns the current particle system
  63355. */
  63356. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  63357. if (!this._sizeGradients) {
  63358. this._sizeGradients = [];
  63359. }
  63360. this._addFactorGradient(this._sizeGradients, gradient, factor);
  63361. if (this._sizeGradientsTexture) {
  63362. this._sizeGradientsTexture.dispose();
  63363. this._sizeGradientsTexture = null;
  63364. }
  63365. this._releaseBuffers();
  63366. return this;
  63367. };
  63368. /**
  63369. * Remove a specific size gradient
  63370. * @param gradient defines the gradient to remove
  63371. * @returns the current particle system
  63372. */
  63373. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  63374. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  63375. this._sizeGradientsTexture = null;
  63376. return this;
  63377. };
  63378. /**
  63379. * Adds a new angular speed gradient
  63380. * @param gradient defines the gradient to use (between 0 and 1)
  63381. * @param factor defines the angular speed to affect to the specified gradient
  63382. * @returns the current particle system
  63383. */
  63384. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  63385. if (!this._angularSpeedGradients) {
  63386. this._angularSpeedGradients = [];
  63387. }
  63388. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  63389. if (this._angularSpeedGradientsTexture) {
  63390. this._angularSpeedGradientsTexture.dispose();
  63391. this._angularSpeedGradientsTexture = null;
  63392. }
  63393. this._releaseBuffers();
  63394. return this;
  63395. };
  63396. /**
  63397. * Remove a specific angular speed gradient
  63398. * @param gradient defines the gradient to remove
  63399. * @returns the current particle system
  63400. */
  63401. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  63402. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  63403. this._angularSpeedGradientsTexture = null;
  63404. return this;
  63405. };
  63406. /**
  63407. * Adds a new velocity gradient
  63408. * @param gradient defines the gradient to use (between 0 and 1)
  63409. * @param factor defines the velocity to affect to the specified gradient
  63410. * @returns the current particle system
  63411. */
  63412. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  63413. if (!this._velocityGradients) {
  63414. this._velocityGradients = [];
  63415. }
  63416. this._addFactorGradient(this._velocityGradients, gradient, factor);
  63417. if (this._velocityGradientsTexture) {
  63418. this._velocityGradientsTexture.dispose();
  63419. this._velocityGradientsTexture = null;
  63420. }
  63421. this._releaseBuffers();
  63422. return this;
  63423. };
  63424. /**
  63425. * Remove a specific velocity gradient
  63426. * @param gradient defines the gradient to remove
  63427. * @returns the current particle system
  63428. */
  63429. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  63430. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  63431. this._velocityGradientsTexture = null;
  63432. return this;
  63433. };
  63434. /**
  63435. * Adds a new limit velocity gradient
  63436. * @param gradient defines the gradient to use (between 0 and 1)
  63437. * @param factor defines the limit velocity value to affect to the specified gradient
  63438. * @returns the current particle system
  63439. */
  63440. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  63441. if (!this._limitVelocityGradients) {
  63442. this._limitVelocityGradients = [];
  63443. }
  63444. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  63445. if (this._limitVelocityGradientsTexture) {
  63446. this._limitVelocityGradientsTexture.dispose();
  63447. this._limitVelocityGradientsTexture = null;
  63448. }
  63449. this._releaseBuffers();
  63450. return this;
  63451. };
  63452. /**
  63453. * Remove a specific limit velocity gradient
  63454. * @param gradient defines the gradient to remove
  63455. * @returns the current particle system
  63456. */
  63457. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  63458. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  63459. this._limitVelocityGradientsTexture = null;
  63460. return this;
  63461. };
  63462. /**
  63463. * Adds a new drag gradient
  63464. * @param gradient defines the gradient to use (between 0 and 1)
  63465. * @param factor defines the drag value to affect to the specified gradient
  63466. * @returns the current particle system
  63467. */
  63468. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  63469. if (!this._dragGradients) {
  63470. this._dragGradients = [];
  63471. }
  63472. this._addFactorGradient(this._dragGradients, gradient, factor);
  63473. if (this._dragGradientsTexture) {
  63474. this._dragGradientsTexture.dispose();
  63475. this._dragGradientsTexture = null;
  63476. }
  63477. this._releaseBuffers();
  63478. return this;
  63479. };
  63480. /**
  63481. * Remove a specific drag gradient
  63482. * @param gradient defines the gradient to remove
  63483. * @returns the current particle system
  63484. */
  63485. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63486. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63487. this._dragGradientsTexture = null;
  63488. return this;
  63489. };
  63490. /**
  63491. * Not supported by GPUParticleSystem
  63492. * @param gradient defines the gradient to use (between 0 and 1)
  63493. * @param factor defines the emit rate value to affect to the specified gradient
  63494. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63495. * @returns the current particle system
  63496. */
  63497. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63498. // Do nothing as emit rate is not supported by GPUParticleSystem
  63499. return this;
  63500. };
  63501. /**
  63502. * Not supported by GPUParticleSystem
  63503. * @param gradient defines the gradient to remove
  63504. * @returns the current particle system
  63505. */
  63506. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63507. // Do nothing as emit rate is not supported by GPUParticleSystem
  63508. return this;
  63509. };
  63510. /**
  63511. * Not supported by GPUParticleSystem
  63512. * @param gradient defines the gradient to use (between 0 and 1)
  63513. * @param factor defines the start size value to affect to the specified gradient
  63514. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63515. * @returns the current particle system
  63516. */
  63517. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63518. // Do nothing as start size is not supported by GPUParticleSystem
  63519. return this;
  63520. };
  63521. /**
  63522. * Not supported by GPUParticleSystem
  63523. * @param gradient defines the gradient to remove
  63524. * @returns the current particle system
  63525. */
  63526. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63527. // Do nothing as start size is not supported by GPUParticleSystem
  63528. return this;
  63529. };
  63530. /**
  63531. * Not supported by GPUParticleSystem
  63532. * @param gradient defines the gradient to use (between 0 and 1)
  63533. * @param min defines the color remap minimal range
  63534. * @param max defines the color remap maximal range
  63535. * @returns the current particle system
  63536. */
  63537. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63538. // Do nothing as start size is not supported by GPUParticleSystem
  63539. return this;
  63540. };
  63541. /**
  63542. * Not supported by GPUParticleSystem
  63543. * @param gradient defines the gradient to remove
  63544. * @returns the current particle system
  63545. */
  63546. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63547. // Do nothing as start size is not supported by GPUParticleSystem
  63548. return this;
  63549. };
  63550. /**
  63551. * Not supported by GPUParticleSystem
  63552. * @param gradient defines the gradient to use (between 0 and 1)
  63553. * @param min defines the alpha remap minimal range
  63554. * @param max defines the alpha remap maximal range
  63555. * @returns the current particle system
  63556. */
  63557. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63558. // Do nothing as start size is not supported by GPUParticleSystem
  63559. return this;
  63560. };
  63561. /**
  63562. * Not supported by GPUParticleSystem
  63563. * @param gradient defines the gradient to remove
  63564. * @returns the current particle system
  63565. */
  63566. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63567. // Do nothing as start size is not supported by GPUParticleSystem
  63568. return this;
  63569. };
  63570. /**
  63571. * Not supported by GPUParticleSystem
  63572. * @param gradient defines the gradient to use (between 0 and 1)
  63573. * @param color defines the color to affect to the specified gradient
  63574. * @returns the current particle system
  63575. */
  63576. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63577. //Not supported by GPUParticleSystem
  63578. return this;
  63579. };
  63580. /**
  63581. * Not supported by GPUParticleSystem
  63582. * @param gradient defines the gradient to remove
  63583. * @returns the current particle system
  63584. */
  63585. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63586. //Not supported by GPUParticleSystem
  63587. return this;
  63588. };
  63589. /**
  63590. * Not supported by GPUParticleSystem
  63591. * @returns the list of ramp gradients
  63592. */
  63593. GPUParticleSystem.prototype.getRampGradients = function () {
  63594. return null;
  63595. };
  63596. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  63597. /**
  63598. * Not supported by GPUParticleSystem
  63599. * Gets or sets a boolean indicating that ramp gradients must be used
  63600. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  63601. */
  63602. get: function () {
  63603. //Not supported by GPUParticleSystem
  63604. return false;
  63605. },
  63606. set: function (value) {
  63607. //Not supported by GPUParticleSystem
  63608. },
  63609. enumerable: true,
  63610. configurable: true
  63611. });
  63612. /**
  63613. * Not supported by GPUParticleSystem
  63614. * @param gradient defines the gradient to use (between 0 and 1)
  63615. * @param factor defines the life time factor to affect to the specified gradient
  63616. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63617. * @returns the current particle system
  63618. */
  63619. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  63620. //Not supported by GPUParticleSystem
  63621. return this;
  63622. };
  63623. /**
  63624. * Not supported by GPUParticleSystem
  63625. * @param gradient defines the gradient to remove
  63626. * @returns the current particle system
  63627. */
  63628. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  63629. //Not supported by GPUParticleSystem
  63630. return this;
  63631. };
  63632. GPUParticleSystem.prototype._reset = function () {
  63633. this._releaseBuffers();
  63634. };
  63635. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63636. var updateVertexBuffers = {};
  63637. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63638. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63639. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63640. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63641. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63642. var offset = 12;
  63643. if (!this._colorGradientsTexture) {
  63644. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63645. offset += 4;
  63646. }
  63647. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63648. offset += 3;
  63649. if (!this._isBillboardBased) {
  63650. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63651. offset += 3;
  63652. }
  63653. if (this._angularSpeedGradientsTexture) {
  63654. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63655. offset += 1;
  63656. }
  63657. else {
  63658. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63659. offset += 2;
  63660. }
  63661. if (this._isAnimationSheetEnabled) {
  63662. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63663. offset += 1;
  63664. if (this.spriteRandomStartCell) {
  63665. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63666. offset += 1;
  63667. }
  63668. }
  63669. if (this.noiseTexture) {
  63670. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63671. offset += 3;
  63672. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63673. offset += 3;
  63674. }
  63675. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63676. this._engine.bindArrayBuffer(null);
  63677. return vao;
  63678. };
  63679. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63680. var renderVertexBuffers = {};
  63681. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63682. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63683. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63684. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63685. var offset = 12;
  63686. if (!this._colorGradientsTexture) {
  63687. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63688. offset += 4;
  63689. }
  63690. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63691. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63692. }
  63693. offset += 3; // Direction
  63694. if (!this._isBillboardBased) {
  63695. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63696. offset += 3;
  63697. }
  63698. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63699. if (this._angularSpeedGradientsTexture) {
  63700. offset++;
  63701. }
  63702. else {
  63703. offset += 2;
  63704. }
  63705. if (this._isAnimationSheetEnabled) {
  63706. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63707. offset += 1;
  63708. if (this.spriteRandomStartCell) {
  63709. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63710. offset += 1;
  63711. }
  63712. }
  63713. if (this.noiseTexture) {
  63714. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63715. offset += 3;
  63716. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63717. offset += 3;
  63718. }
  63719. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63720. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63721. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63722. this._engine.bindArrayBuffer(null);
  63723. return vao;
  63724. };
  63725. GPUParticleSystem.prototype._initialize = function (force) {
  63726. if (force === void 0) { force = false; }
  63727. if (this._buffer0 && !force) {
  63728. return;
  63729. }
  63730. var engine = this._scene.getEngine();
  63731. var data = new Array();
  63732. if (!this.isBillboardBased) {
  63733. this._attributesStrideSize += 3;
  63734. }
  63735. if (this._colorGradientsTexture) {
  63736. this._attributesStrideSize -= 4;
  63737. }
  63738. if (this._angularSpeedGradientsTexture) {
  63739. this._attributesStrideSize -= 1;
  63740. }
  63741. if (this._isAnimationSheetEnabled) {
  63742. this._attributesStrideSize += 1;
  63743. if (this.spriteRandomStartCell) {
  63744. this._attributesStrideSize += 1;
  63745. }
  63746. }
  63747. if (this.noiseTexture) {
  63748. this._attributesStrideSize += 6;
  63749. }
  63750. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63751. // position
  63752. data.push(0.0);
  63753. data.push(0.0);
  63754. data.push(0.0);
  63755. // Age and life
  63756. data.push(0.0); // create the particle as a dead one to create a new one at start
  63757. data.push(0.0);
  63758. // Seed
  63759. data.push(Math.random());
  63760. data.push(Math.random());
  63761. data.push(Math.random());
  63762. data.push(Math.random());
  63763. // Size
  63764. data.push(0.0);
  63765. data.push(0.0);
  63766. data.push(0.0);
  63767. if (!this._colorGradientsTexture) {
  63768. // color
  63769. data.push(0.0);
  63770. data.push(0.0);
  63771. data.push(0.0);
  63772. data.push(0.0);
  63773. }
  63774. // direction
  63775. data.push(0.0);
  63776. data.push(0.0);
  63777. data.push(0.0);
  63778. if (!this.isBillboardBased) {
  63779. // initialDirection
  63780. data.push(0.0);
  63781. data.push(0.0);
  63782. data.push(0.0);
  63783. }
  63784. // angle
  63785. data.push(0.0);
  63786. if (!this._angularSpeedGradientsTexture) {
  63787. data.push(0.0);
  63788. }
  63789. if (this._isAnimationSheetEnabled) {
  63790. data.push(0.0);
  63791. if (this.spriteRandomStartCell) {
  63792. data.push(0.0);
  63793. }
  63794. }
  63795. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  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. data.push(Math.random());
  63802. }
  63803. }
  63804. // Sprite data
  63805. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63806. -0.5, 0.5, 0, 1,
  63807. -0.5, -0.5, 0, 0,
  63808. 0.5, -0.5, 1, 0]);
  63809. // Buffers
  63810. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63811. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63812. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63813. // Update VAO
  63814. this._updateVAO = [];
  63815. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63816. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63817. // Render VAO
  63818. this._renderVAO = [];
  63819. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63820. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63821. // Links
  63822. this._sourceBuffer = this._buffer0;
  63823. this._targetBuffer = this._buffer1;
  63824. };
  63825. /** @hidden */
  63826. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63827. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63828. if (this._isBillboardBased) {
  63829. defines += "\n#define BILLBOARD";
  63830. }
  63831. if (this._colorGradientsTexture) {
  63832. defines += "\n#define COLORGRADIENTS";
  63833. }
  63834. if (this._sizeGradientsTexture) {
  63835. defines += "\n#define SIZEGRADIENTS";
  63836. }
  63837. if (this._angularSpeedGradientsTexture) {
  63838. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63839. }
  63840. if (this._velocityGradientsTexture) {
  63841. defines += "\n#define VELOCITYGRADIENTS";
  63842. }
  63843. if (this._limitVelocityGradientsTexture) {
  63844. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63845. }
  63846. if (this._dragGradientsTexture) {
  63847. defines += "\n#define DRAGGRADIENTS";
  63848. }
  63849. if (this.isAnimationSheetEnabled) {
  63850. defines += "\n#define ANIMATESHEET";
  63851. if (this.spriteRandomStartCell) {
  63852. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63853. }
  63854. }
  63855. if (this.noiseTexture) {
  63856. defines += "\n#define NOISE";
  63857. }
  63858. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63859. return;
  63860. }
  63861. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63862. if (!this._colorGradientsTexture) {
  63863. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63864. }
  63865. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63866. if (!this._isBillboardBased) {
  63867. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63868. }
  63869. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63870. if (this.isAnimationSheetEnabled) {
  63871. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63872. if (this.spriteRandomStartCell) {
  63873. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63874. }
  63875. }
  63876. if (this.noiseTexture) {
  63877. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63878. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63879. }
  63880. this._updateEffectOptions.defines = defines;
  63881. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63882. };
  63883. /** @hidden */
  63884. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63885. var defines = "";
  63886. if (this._scene.clipPlane) {
  63887. defines = "\n#define CLIPPLANE";
  63888. }
  63889. if (this._scene.clipPlane2) {
  63890. defines = "\n#define CLIPPLANE2";
  63891. }
  63892. if (this._scene.clipPlane3) {
  63893. defines = "\n#define CLIPPLANE3";
  63894. }
  63895. if (this._scene.clipPlane4) {
  63896. defines = "\n#define CLIPPLANE4";
  63897. }
  63898. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63899. defines = "\n#define BLENDMULTIPLYMODE";
  63900. }
  63901. if (this._isBillboardBased) {
  63902. defines += "\n#define BILLBOARD";
  63903. switch (this.billboardMode) {
  63904. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63905. defines += "\n#define BILLBOARDY";
  63906. break;
  63907. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63908. defines += "\n#define BILLBOARDSTRETCHED";
  63909. break;
  63910. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63911. default:
  63912. break;
  63913. }
  63914. }
  63915. if (this._colorGradientsTexture) {
  63916. defines += "\n#define COLORGRADIENTS";
  63917. }
  63918. if (this.isAnimationSheetEnabled) {
  63919. defines += "\n#define ANIMATESHEET";
  63920. }
  63921. if (this._imageProcessingConfiguration) {
  63922. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63923. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63924. }
  63925. if (this._renderEffect && this._renderEffect.defines === defines) {
  63926. return;
  63927. }
  63928. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63929. var samplers = ["textureSampler", "colorGradientSampler"];
  63930. if (BABYLON.ImageProcessingConfiguration) {
  63931. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63932. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63933. }
  63934. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63935. };
  63936. /**
  63937. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63938. * @param preWarm defines if we are in the pre-warmimg phase
  63939. */
  63940. GPUParticleSystem.prototype.animate = function (preWarm) {
  63941. if (preWarm === void 0) { preWarm = false; }
  63942. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63943. this._actualFrame += this._timeDelta;
  63944. if (!this._stopped) {
  63945. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63946. this.stop();
  63947. }
  63948. }
  63949. };
  63950. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63951. var texture = this[textureName];
  63952. if (!factorGradients || !factorGradients.length || texture) {
  63953. return;
  63954. }
  63955. var data = new Float32Array(this._rawTextureWidth);
  63956. for (var x = 0; x < this._rawTextureWidth; x++) {
  63957. var ratio = x / this._rawTextureWidth;
  63958. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63959. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63960. });
  63961. }
  63962. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63963. };
  63964. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63965. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63966. };
  63967. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63968. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63969. };
  63970. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63971. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63972. };
  63973. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63974. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63975. };
  63976. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63977. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63978. };
  63979. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63980. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63981. return;
  63982. }
  63983. var data = new Uint8Array(this._rawTextureWidth * 4);
  63984. var tmpColor = BABYLON.Tmp.Color4[0];
  63985. for (var x = 0; x < this._rawTextureWidth; x++) {
  63986. var ratio = x / this._rawTextureWidth;
  63987. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63988. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63989. data[x * 4] = tmpColor.r * 255;
  63990. data[x * 4 + 1] = tmpColor.g * 255;
  63991. data[x * 4 + 2] = tmpColor.b * 255;
  63992. data[x * 4 + 3] = tmpColor.a * 255;
  63993. });
  63994. }
  63995. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63996. };
  63997. /**
  63998. * Renders the particle system in its current state
  63999. * @param preWarm defines if the system should only update the particles but not render them
  64000. * @returns the current number of particles
  64001. */
  64002. GPUParticleSystem.prototype.render = function (preWarm) {
  64003. if (preWarm === void 0) { preWarm = false; }
  64004. if (!this._started) {
  64005. return 0;
  64006. }
  64007. this._createColorGradientTexture();
  64008. this._createSizeGradientTexture();
  64009. this._createAngularSpeedGradientTexture();
  64010. this._createVelocityGradientTexture();
  64011. this._createLimitVelocityGradientTexture();
  64012. this._createDragGradientTexture();
  64013. this._recreateUpdateEffect();
  64014. this._recreateRenderEffect();
  64015. if (!this.isReady()) {
  64016. return 0;
  64017. }
  64018. if (!preWarm) {
  64019. if (!this._preWarmDone && this.preWarmCycles) {
  64020. for (var index = 0; index < this.preWarmCycles; index++) {
  64021. this.animate(true);
  64022. this.render(true);
  64023. }
  64024. this._preWarmDone = true;
  64025. }
  64026. if (this._currentRenderId === this._scene.getRenderId()) {
  64027. return 0;
  64028. }
  64029. this._currentRenderId = this._scene.getRenderId();
  64030. }
  64031. // Get everything ready to render
  64032. this._initialize();
  64033. this._accumulatedCount += this.emitRate * this._timeDelta;
  64034. if (this._accumulatedCount > 1) {
  64035. var intPart = this._accumulatedCount | 0;
  64036. this._accumulatedCount -= intPart;
  64037. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  64038. }
  64039. if (!this._currentActiveCount) {
  64040. return 0;
  64041. }
  64042. // Enable update effect
  64043. this._engine.enableEffect(this._updateEffect);
  64044. this._engine.setState(false);
  64045. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  64046. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  64047. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  64048. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  64049. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  64050. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  64051. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  64052. if (!this._colorGradientsTexture) {
  64053. this._updateEffect.setDirectColor4("color1", this.color1);
  64054. this._updateEffect.setDirectColor4("color2", this.color2);
  64055. }
  64056. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  64057. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  64058. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  64059. this._updateEffect.setVector3("gravity", this.gravity);
  64060. if (this._sizeGradientsTexture) {
  64061. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  64062. }
  64063. if (this._angularSpeedGradientsTexture) {
  64064. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  64065. }
  64066. if (this._velocityGradientsTexture) {
  64067. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  64068. }
  64069. if (this._limitVelocityGradientsTexture) {
  64070. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  64071. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  64072. }
  64073. if (this._dragGradientsTexture) {
  64074. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  64075. }
  64076. if (this.particleEmitterType) {
  64077. this.particleEmitterType.applyToShader(this._updateEffect);
  64078. }
  64079. if (this._isAnimationSheetEnabled) {
  64080. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  64081. }
  64082. if (this.noiseTexture) {
  64083. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  64084. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  64085. }
  64086. var emitterWM;
  64087. if (this.emitter.position) {
  64088. var emitterMesh = this.emitter;
  64089. emitterWM = emitterMesh.getWorldMatrix();
  64090. }
  64091. else {
  64092. var emitterPosition = this.emitter;
  64093. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  64094. }
  64095. this._updateEffect.setMatrix("emitterWM", emitterWM);
  64096. // Bind source VAO
  64097. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  64098. // Update
  64099. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  64100. this._engine.setRasterizerState(false);
  64101. this._engine.beginTransformFeedback(true);
  64102. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  64103. this._engine.endTransformFeedback();
  64104. this._engine.setRasterizerState(true);
  64105. this._engine.bindTransformFeedbackBuffer(null);
  64106. if (!preWarm) {
  64107. // Enable render effect
  64108. this._engine.enableEffect(this._renderEffect);
  64109. var viewMatrix = this._scene.getViewMatrix();
  64110. this._renderEffect.setMatrix("view", viewMatrix);
  64111. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  64112. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  64113. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  64114. if (this._colorGradientsTexture) {
  64115. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  64116. }
  64117. else {
  64118. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  64119. }
  64120. if (this._isAnimationSheetEnabled && this.particleTexture) {
  64121. var baseSize = this.particleTexture.getBaseSize();
  64122. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  64123. }
  64124. if (this._isBillboardBased) {
  64125. var camera = this._scene.activeCamera;
  64126. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  64127. }
  64128. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  64129. var invView = viewMatrix.clone();
  64130. invView.invert();
  64131. this._renderEffect.setMatrix("invView", invView);
  64132. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  64133. }
  64134. // image processing
  64135. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  64136. this._imageProcessingConfiguration.bind(this._renderEffect);
  64137. }
  64138. // Draw order
  64139. switch (this.blendMode) {
  64140. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  64141. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  64142. break;
  64143. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  64144. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  64145. break;
  64146. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  64147. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64148. break;
  64149. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  64150. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  64151. break;
  64152. }
  64153. if (this.forceDepthWrite) {
  64154. this._engine.setDepthWrite(true);
  64155. }
  64156. // Bind source VAO
  64157. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  64158. // Render
  64159. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  64160. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64161. }
  64162. // Switch VAOs
  64163. this._targetIndex++;
  64164. if (this._targetIndex === 2) {
  64165. this._targetIndex = 0;
  64166. }
  64167. // Switch buffers
  64168. var tmpBuffer = this._sourceBuffer;
  64169. this._sourceBuffer = this._targetBuffer;
  64170. this._targetBuffer = tmpBuffer;
  64171. return this._currentActiveCount;
  64172. };
  64173. /**
  64174. * Rebuilds the particle system
  64175. */
  64176. GPUParticleSystem.prototype.rebuild = function () {
  64177. this._initialize(true);
  64178. };
  64179. GPUParticleSystem.prototype._releaseBuffers = function () {
  64180. if (this._buffer0) {
  64181. this._buffer0.dispose();
  64182. this._buffer0 = null;
  64183. }
  64184. if (this._buffer1) {
  64185. this._buffer1.dispose();
  64186. this._buffer1 = null;
  64187. }
  64188. if (this._spriteBuffer) {
  64189. this._spriteBuffer.dispose();
  64190. this._spriteBuffer = null;
  64191. }
  64192. };
  64193. GPUParticleSystem.prototype._releaseVAOs = function () {
  64194. if (!this._updateVAO) {
  64195. return;
  64196. }
  64197. for (var index = 0; index < this._updateVAO.length; index++) {
  64198. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  64199. }
  64200. this._updateVAO = [];
  64201. for (var index = 0; index < this._renderVAO.length; index++) {
  64202. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  64203. }
  64204. this._renderVAO = [];
  64205. };
  64206. /**
  64207. * Disposes the particle system and free the associated resources
  64208. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  64209. */
  64210. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  64211. if (disposeTexture === void 0) { disposeTexture = true; }
  64212. var index = this._scene.particleSystems.indexOf(this);
  64213. if (index > -1) {
  64214. this._scene.particleSystems.splice(index, 1);
  64215. }
  64216. this._releaseBuffers();
  64217. this._releaseVAOs();
  64218. if (this._colorGradientsTexture) {
  64219. this._colorGradientsTexture.dispose();
  64220. this._colorGradientsTexture = null;
  64221. }
  64222. if (this._sizeGradientsTexture) {
  64223. this._sizeGradientsTexture.dispose();
  64224. this._sizeGradientsTexture = null;
  64225. }
  64226. if (this._angularSpeedGradientsTexture) {
  64227. this._angularSpeedGradientsTexture.dispose();
  64228. this._angularSpeedGradientsTexture = null;
  64229. }
  64230. if (this._velocityGradientsTexture) {
  64231. this._velocityGradientsTexture.dispose();
  64232. this._velocityGradientsTexture = null;
  64233. }
  64234. if (this._limitVelocityGradientsTexture) {
  64235. this._limitVelocityGradientsTexture.dispose();
  64236. this._limitVelocityGradientsTexture = null;
  64237. }
  64238. if (this._dragGradientsTexture) {
  64239. this._dragGradientsTexture.dispose();
  64240. this._dragGradientsTexture = null;
  64241. }
  64242. if (this._randomTexture) {
  64243. this._randomTexture.dispose();
  64244. this._randomTexture = null;
  64245. }
  64246. if (this._randomTexture2) {
  64247. this._randomTexture2.dispose();
  64248. this._randomTexture2 = null;
  64249. }
  64250. if (disposeTexture && this.particleTexture) {
  64251. this.particleTexture.dispose();
  64252. this.particleTexture = null;
  64253. }
  64254. if (disposeTexture && this.noiseTexture) {
  64255. this.noiseTexture.dispose();
  64256. this.noiseTexture = null;
  64257. }
  64258. // Callback
  64259. this.onDisposeObservable.notifyObservers(this);
  64260. this.onDisposeObservable.clear();
  64261. };
  64262. /**
  64263. * Clones the particle system.
  64264. * @param name The name of the cloned object
  64265. * @param newEmitter The new emitter to use
  64266. * @returns the cloned particle system
  64267. */
  64268. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  64269. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  64270. BABYLON.Tools.DeepCopy(this, result);
  64271. if (newEmitter === undefined) {
  64272. newEmitter = this.emitter;
  64273. }
  64274. result.emitter = newEmitter;
  64275. if (this.particleTexture) {
  64276. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  64277. }
  64278. return result;
  64279. };
  64280. /**
  64281. * Serializes the particle system to a JSON object.
  64282. * @returns the JSON object
  64283. */
  64284. GPUParticleSystem.prototype.serialize = function () {
  64285. var serializationObject = {};
  64286. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  64287. serializationObject.activeParticleCount = this.activeParticleCount;
  64288. return serializationObject;
  64289. };
  64290. /**
  64291. * Parses a JSON object to create a GPU particle system.
  64292. * @param parsedParticleSystem The JSON object to parse
  64293. * @param scene The scene to create the particle system in
  64294. * @param rootUrl The root url to use to load external dependencies like texture
  64295. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  64296. * @returns the parsed GPU particle system
  64297. */
  64298. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  64299. if (doNotStart === void 0) { doNotStart = false; }
  64300. var name = parsedParticleSystem.name;
  64301. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  64302. if (parsedParticleSystem.activeParticleCount) {
  64303. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  64304. }
  64305. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  64306. // Auto start
  64307. if (parsedParticleSystem.preventAutoStart) {
  64308. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  64309. }
  64310. if (!doNotStart && !particleSystem.preventAutoStart) {
  64311. particleSystem.start();
  64312. }
  64313. return particleSystem;
  64314. };
  64315. return GPUParticleSystem;
  64316. }(BABYLON.BaseParticleSystem));
  64317. BABYLON.GPUParticleSystem = GPUParticleSystem;
  64318. })(BABYLON || (BABYLON = {}));
  64319. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  64320. var BABYLON;
  64321. (function (BABYLON) {
  64322. /**
  64323. * Represents one particle of a solid particle system.
  64324. */
  64325. var SolidParticle = /** @class */ (function () {
  64326. /**
  64327. * Creates a Solid Particle object.
  64328. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  64329. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  64330. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  64331. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  64332. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  64333. * @param shapeId (integer) is the model shape identifier in the SPS.
  64334. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  64335. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  64336. */
  64337. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  64338. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  64339. /**
  64340. * particle global index
  64341. */
  64342. this.idx = 0;
  64343. /**
  64344. * The color of the particle
  64345. */
  64346. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64347. /**
  64348. * The world space position of the particle.
  64349. */
  64350. this.position = BABYLON.Vector3.Zero();
  64351. /**
  64352. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  64353. */
  64354. this.rotation = BABYLON.Vector3.Zero();
  64355. /**
  64356. * The scaling of the particle.
  64357. */
  64358. this.scaling = BABYLON.Vector3.One();
  64359. /**
  64360. * The uvs of the particle.
  64361. */
  64362. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  64363. /**
  64364. * The current speed of the particle.
  64365. */
  64366. this.velocity = BABYLON.Vector3.Zero();
  64367. /**
  64368. * The pivot point in the particle local space.
  64369. */
  64370. this.pivot = BABYLON.Vector3.Zero();
  64371. /**
  64372. * Must the particle be translated from its pivot point in its local space ?
  64373. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  64374. * Default : false
  64375. */
  64376. this.translateFromPivot = false;
  64377. /**
  64378. * Is the particle active or not ?
  64379. */
  64380. this.alive = true;
  64381. /**
  64382. * Is the particle visible or not ?
  64383. */
  64384. this.isVisible = true;
  64385. /**
  64386. * Index of this particle in the global "positions" array (Internal use)
  64387. * @hidden
  64388. */
  64389. this._pos = 0;
  64390. /**
  64391. * @hidden Index of this particle in the global "indices" array (Internal use)
  64392. */
  64393. this._ind = 0;
  64394. /**
  64395. * ModelShape id of this particle
  64396. */
  64397. this.shapeId = 0;
  64398. /**
  64399. * Index of the particle in its shape id (Internal use)
  64400. */
  64401. this.idxInShape = 0;
  64402. /**
  64403. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  64404. */
  64405. this._stillInvisible = false;
  64406. /**
  64407. * @hidden Last computed particle rotation matrix
  64408. */
  64409. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  64410. /**
  64411. * Parent particle Id, if any.
  64412. * Default null.
  64413. */
  64414. this.parentId = null;
  64415. /**
  64416. * @hidden Internal global position in the SPS.
  64417. */
  64418. this._globalPosition = BABYLON.Vector3.Zero();
  64419. this.idx = particleIndex;
  64420. this._pos = positionIndex;
  64421. this._ind = indiceIndex;
  64422. this._model = model;
  64423. this.shapeId = shapeId;
  64424. this.idxInShape = idxInShape;
  64425. this._sps = sps;
  64426. if (modelBoundingInfo) {
  64427. this._modelBoundingInfo = modelBoundingInfo;
  64428. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  64429. }
  64430. }
  64431. Object.defineProperty(SolidParticle.prototype, "scale", {
  64432. /**
  64433. * Legacy support, changed scale to scaling
  64434. */
  64435. get: function () {
  64436. return this.scaling;
  64437. },
  64438. /**
  64439. * Legacy support, changed scale to scaling
  64440. */
  64441. set: function (scale) {
  64442. this.scaling = scale;
  64443. },
  64444. enumerable: true,
  64445. configurable: true
  64446. });
  64447. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  64448. /**
  64449. * Legacy support, changed quaternion to rotationQuaternion
  64450. */
  64451. get: function () {
  64452. return this.rotationQuaternion;
  64453. },
  64454. /**
  64455. * Legacy support, changed quaternion to rotationQuaternion
  64456. */
  64457. set: function (q) {
  64458. this.rotationQuaternion = q;
  64459. },
  64460. enumerable: true,
  64461. configurable: true
  64462. });
  64463. /**
  64464. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  64465. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  64466. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  64467. * @returns true if it intersects
  64468. */
  64469. SolidParticle.prototype.intersectsMesh = function (target) {
  64470. if (!this._boundingInfo || !target._boundingInfo) {
  64471. return false;
  64472. }
  64473. if (this._sps._bSphereOnly) {
  64474. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  64475. }
  64476. return this._boundingInfo.intersects(target._boundingInfo, false);
  64477. };
  64478. return SolidParticle;
  64479. }());
  64480. BABYLON.SolidParticle = SolidParticle;
  64481. /**
  64482. * Represents the shape of the model used by one particle of a solid particle system.
  64483. * SPS internal tool, don't use it manually.
  64484. */
  64485. var ModelShape = /** @class */ (function () {
  64486. /**
  64487. * 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.
  64488. * SPS internal tool, don't use it manually.
  64489. * @hidden
  64490. */
  64491. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  64492. /**
  64493. * length of the shape in the model indices array (internal use)
  64494. * @hidden
  64495. */
  64496. this._indicesLength = 0;
  64497. this.shapeID = id;
  64498. this._shape = shape;
  64499. this._indicesLength = indicesLength;
  64500. this._shapeUV = shapeUV;
  64501. this._positionFunction = posFunction;
  64502. this._vertexFunction = vtxFunction;
  64503. }
  64504. return ModelShape;
  64505. }());
  64506. BABYLON.ModelShape = ModelShape;
  64507. /**
  64508. * Represents a Depth Sorted Particle in the solid particle system.
  64509. */
  64510. var DepthSortedParticle = /** @class */ (function () {
  64511. function DepthSortedParticle() {
  64512. /**
  64513. * Index of the particle in the "indices" array
  64514. */
  64515. this.ind = 0;
  64516. /**
  64517. * Length of the particle shape in the "indices" array
  64518. */
  64519. this.indicesLength = 0;
  64520. /**
  64521. * Squared distance from the particle to the camera
  64522. */
  64523. this.sqDistance = 0.0;
  64524. }
  64525. return DepthSortedParticle;
  64526. }());
  64527. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64528. })(BABYLON || (BABYLON = {}));
  64529. //# sourceMappingURL=babylon.solidParticle.js.map
  64530. var BABYLON;
  64531. (function (BABYLON) {
  64532. /**
  64533. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64534. *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.
  64535. * The SPS is also a particle system. It provides some methods to manage the particles.
  64536. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64537. *
  64538. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64539. */
  64540. var SolidParticleSystem = /** @class */ (function () {
  64541. /**
  64542. * Creates a SPS (Solid Particle System) object.
  64543. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64544. * @param scene (Scene) is the scene in which the SPS is added.
  64545. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64546. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64547. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64548. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64549. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64550. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64551. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64552. */
  64553. function SolidParticleSystem(name, scene, options) {
  64554. /**
  64555. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64556. * Example : var p = SPS.particles[i];
  64557. */
  64558. this.particles = new Array();
  64559. /**
  64560. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64561. */
  64562. this.nbParticles = 0;
  64563. /**
  64564. * If the particles must ever face the camera (default false). Useful for planar particles.
  64565. */
  64566. this.billboard = false;
  64567. /**
  64568. * Recompute normals when adding a shape
  64569. */
  64570. this.recomputeNormals = true;
  64571. /**
  64572. * This a counter ofr your own usage. It's not set by any SPS functions.
  64573. */
  64574. this.counter = 0;
  64575. /**
  64576. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64577. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64578. */
  64579. this.vars = {};
  64580. /**
  64581. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64582. * @hidden
  64583. */
  64584. this._bSphereOnly = false;
  64585. /**
  64586. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64587. * @hidden
  64588. */
  64589. this._bSphereRadiusFactor = 1.0;
  64590. this._positions = new Array();
  64591. this._indices = new Array();
  64592. this._normals = new Array();
  64593. this._colors = new Array();
  64594. this._uvs = new Array();
  64595. this._index = 0; // indices index
  64596. this._updatable = true;
  64597. this._pickable = false;
  64598. this._isVisibilityBoxLocked = false;
  64599. this._alwaysVisible = false;
  64600. this._depthSort = false;
  64601. this._shapeCounter = 0;
  64602. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64603. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64604. this._computeParticleColor = true;
  64605. this._computeParticleTexture = true;
  64606. this._computeParticleRotation = true;
  64607. this._computeParticleVertex = false;
  64608. this._computeBoundingBox = false;
  64609. this._depthSortParticles = true;
  64610. this._cam_axisZ = BABYLON.Vector3.Zero();
  64611. this._cam_axisY = BABYLON.Vector3.Zero();
  64612. this._cam_axisX = BABYLON.Vector3.Zero();
  64613. this._axisZ = BABYLON.Axis.Z;
  64614. this._camDir = BABYLON.Vector3.Zero();
  64615. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64616. this._rotMatrix = new BABYLON.Matrix();
  64617. this._invertMatrix = new BABYLON.Matrix();
  64618. this._rotated = BABYLON.Vector3.Zero();
  64619. this._quaternion = new BABYLON.Quaternion();
  64620. this._vertex = BABYLON.Vector3.Zero();
  64621. this._normal = BABYLON.Vector3.Zero();
  64622. this._yaw = 0.0;
  64623. this._pitch = 0.0;
  64624. this._roll = 0.0;
  64625. this._halfroll = 0.0;
  64626. this._halfpitch = 0.0;
  64627. this._halfyaw = 0.0;
  64628. this._sinRoll = 0.0;
  64629. this._cosRoll = 0.0;
  64630. this._sinPitch = 0.0;
  64631. this._cosPitch = 0.0;
  64632. this._sinYaw = 0.0;
  64633. this._cosYaw = 0.0;
  64634. this._mustUnrotateFixedNormals = false;
  64635. this._minimum = BABYLON.Vector3.Zero();
  64636. this._maximum = BABYLON.Vector3.Zero();
  64637. this._minBbox = BABYLON.Vector3.Zero();
  64638. this._maxBbox = BABYLON.Vector3.Zero();
  64639. this._particlesIntersect = false;
  64640. this._depthSortFunction = function (p1, p2) {
  64641. return (p2.sqDistance - p1.sqDistance);
  64642. };
  64643. this._needs32Bits = false;
  64644. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64645. this._scaledPivot = BABYLON.Vector3.Zero();
  64646. this._particleHasParent = false;
  64647. this.name = name;
  64648. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64649. this._camera = scene.activeCamera;
  64650. this._pickable = options ? options.isPickable : false;
  64651. this._depthSort = options ? options.enableDepthSort : false;
  64652. this._particlesIntersect = options ? options.particleIntersection : false;
  64653. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64654. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64655. if (options && options.updatable !== undefined) {
  64656. this._updatable = options.updatable;
  64657. }
  64658. else {
  64659. this._updatable = true;
  64660. }
  64661. if (this._pickable) {
  64662. this.pickedParticles = [];
  64663. }
  64664. if (this._depthSort) {
  64665. this.depthSortedParticles = [];
  64666. }
  64667. }
  64668. /**
  64669. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64670. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64671. * @returns the created mesh
  64672. */
  64673. SolidParticleSystem.prototype.buildMesh = function () {
  64674. if (this.nbParticles === 0) {
  64675. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64676. this.addShape(triangle, 1);
  64677. triangle.dispose();
  64678. }
  64679. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64680. this._positions32 = new Float32Array(this._positions);
  64681. this._uvs32 = new Float32Array(this._uvs);
  64682. this._colors32 = new Float32Array(this._colors);
  64683. if (this.recomputeNormals) {
  64684. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64685. }
  64686. this._normals32 = new Float32Array(this._normals);
  64687. this._fixedNormal32 = new Float32Array(this._normals);
  64688. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64689. this._unrotateFixedNormals();
  64690. }
  64691. var vertexData = new BABYLON.VertexData();
  64692. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64693. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64694. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64695. if (this._uvs32.length > 0) {
  64696. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64697. }
  64698. if (this._colors32.length > 0) {
  64699. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64700. }
  64701. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64702. vertexData.applyToMesh(mesh, this._updatable);
  64703. this.mesh = mesh;
  64704. this.mesh.isPickable = this._pickable;
  64705. // free memory
  64706. if (!this._depthSort) {
  64707. this._indices = null;
  64708. }
  64709. this._positions = null;
  64710. this._normals = null;
  64711. this._uvs = null;
  64712. this._colors = null;
  64713. if (!this._updatable) {
  64714. this.particles.length = 0;
  64715. }
  64716. return mesh;
  64717. };
  64718. /**
  64719. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64720. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64721. * Thus the particles generated from `digest()` have their property `position` set yet.
  64722. * @param mesh ( Mesh ) is the mesh to be digested
  64723. * @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
  64724. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64725. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64726. * @returns the current SPS
  64727. */
  64728. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64729. var size = (options && options.facetNb) || 1;
  64730. var number = (options && options.number) || 0;
  64731. var delta = (options && options.delta) || 0;
  64732. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64733. var meshInd = mesh.getIndices();
  64734. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64735. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64736. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64737. var f = 0; // facet counter
  64738. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64739. // compute size from number
  64740. if (number) {
  64741. number = (number > totalFacets) ? totalFacets : number;
  64742. size = Math.round(totalFacets / number);
  64743. delta = 0;
  64744. }
  64745. else {
  64746. size = (size > totalFacets) ? totalFacets : size;
  64747. }
  64748. var facetPos = []; // submesh positions
  64749. var facetInd = []; // submesh indices
  64750. var facetUV = []; // submesh UV
  64751. var facetCol = []; // submesh colors
  64752. var barycenter = BABYLON.Vector3.Zero();
  64753. var sizeO = size;
  64754. while (f < totalFacets) {
  64755. size = sizeO + Math.floor((1 + delta) * Math.random());
  64756. if (f > totalFacets - size) {
  64757. size = totalFacets - f;
  64758. }
  64759. // reset temp arrays
  64760. facetPos.length = 0;
  64761. facetInd.length = 0;
  64762. facetUV.length = 0;
  64763. facetCol.length = 0;
  64764. // iterate over "size" facets
  64765. var fi = 0;
  64766. for (var j = f * 3; j < (f + size) * 3; j++) {
  64767. facetInd.push(fi);
  64768. var i = meshInd[j];
  64769. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64770. if (meshUV) {
  64771. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64772. }
  64773. if (meshCol) {
  64774. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64775. }
  64776. fi++;
  64777. }
  64778. // create a model shape for each single particle
  64779. var idx = this.nbParticles;
  64780. var shape = this._posToShape(facetPos);
  64781. var shapeUV = this._uvsToShapeUV(facetUV);
  64782. // compute the barycenter of the shape
  64783. var v;
  64784. for (v = 0; v < shape.length; v++) {
  64785. barycenter.addInPlace(shape[v]);
  64786. }
  64787. barycenter.scaleInPlace(1 / shape.length);
  64788. // shift the shape from its barycenter to the origin
  64789. for (v = 0; v < shape.length; v++) {
  64790. shape[v].subtractInPlace(barycenter);
  64791. }
  64792. var bInfo;
  64793. if (this._particlesIntersect) {
  64794. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64795. }
  64796. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64797. // add the particle in the SPS
  64798. var currentPos = this._positions.length;
  64799. var currentInd = this._indices.length;
  64800. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64801. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64802. // initialize the particle position
  64803. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64804. this._index += shape.length;
  64805. idx++;
  64806. this.nbParticles++;
  64807. this._shapeCounter++;
  64808. f += size;
  64809. }
  64810. return this;
  64811. };
  64812. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64813. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64814. var index = 0;
  64815. var idx = 0;
  64816. for (var p = 0; p < this.particles.length; p++) {
  64817. this._particle = this.particles[p];
  64818. this._shape = this._particle._model._shape;
  64819. if (this._particle.rotationQuaternion) {
  64820. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64821. }
  64822. else {
  64823. this._yaw = this._particle.rotation.y;
  64824. this._pitch = this._particle.rotation.x;
  64825. this._roll = this._particle.rotation.z;
  64826. this._quaternionRotationYPR();
  64827. }
  64828. this._quaternionToRotationMatrix();
  64829. this._rotMatrix.invertToRef(this._invertMatrix);
  64830. for (var pt = 0; pt < this._shape.length; pt++) {
  64831. idx = index + pt * 3;
  64832. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64833. this._fixedNormal32[idx] = this._normal.x;
  64834. this._fixedNormal32[idx + 1] = this._normal.y;
  64835. this._fixedNormal32[idx + 2] = this._normal.z;
  64836. }
  64837. index = idx + 3;
  64838. }
  64839. };
  64840. //reset copy
  64841. SolidParticleSystem.prototype._resetCopy = function () {
  64842. this._copy.position.x = 0;
  64843. this._copy.position.y = 0;
  64844. this._copy.position.z = 0;
  64845. this._copy.rotation.x = 0;
  64846. this._copy.rotation.y = 0;
  64847. this._copy.rotation.z = 0;
  64848. this._copy.rotationQuaternion = null;
  64849. this._copy.scaling.x = 1.0;
  64850. this._copy.scaling.y = 1.0;
  64851. this._copy.scaling.z = 1.0;
  64852. this._copy.uvs.x = 0;
  64853. this._copy.uvs.y = 0;
  64854. this._copy.uvs.z = 1.0;
  64855. this._copy.uvs.w = 1.0;
  64856. this._copy.color = null;
  64857. this._copy.translateFromPivot = false;
  64858. };
  64859. // _meshBuilder : inserts the shape model in the global SPS mesh
  64860. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64861. var i;
  64862. var u = 0;
  64863. var c = 0;
  64864. var n = 0;
  64865. this._resetCopy();
  64866. if (options && options.positionFunction) { // call to custom positionFunction
  64867. options.positionFunction(this._copy, idx, idxInShape);
  64868. this._mustUnrotateFixedNormals = true;
  64869. }
  64870. if (this._copy.rotationQuaternion) {
  64871. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64872. }
  64873. else {
  64874. this._yaw = this._copy.rotation.y;
  64875. this._pitch = this._copy.rotation.x;
  64876. this._roll = this._copy.rotation.z;
  64877. this._quaternionRotationYPR();
  64878. }
  64879. this._quaternionToRotationMatrix();
  64880. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64881. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64882. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64883. if (this._copy.translateFromPivot) {
  64884. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64885. }
  64886. else {
  64887. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64888. }
  64889. for (i = 0; i < shape.length; i++) {
  64890. this._vertex.x = shape[i].x;
  64891. this._vertex.y = shape[i].y;
  64892. this._vertex.z = shape[i].z;
  64893. if (options && options.vertexFunction) {
  64894. options.vertexFunction(this._copy, this._vertex, i);
  64895. }
  64896. this._vertex.x *= this._copy.scaling.x;
  64897. this._vertex.y *= this._copy.scaling.y;
  64898. this._vertex.z *= this._copy.scaling.z;
  64899. this._vertex.x -= this._scaledPivot.x;
  64900. this._vertex.y -= this._scaledPivot.y;
  64901. this._vertex.z -= this._scaledPivot.z;
  64902. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64903. this._rotated.addInPlace(this._pivotBackTranslation);
  64904. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64905. if (meshUV) {
  64906. 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);
  64907. u += 2;
  64908. }
  64909. if (this._copy.color) {
  64910. this._color = this._copy.color;
  64911. }
  64912. else if (meshCol && meshCol[c] !== undefined) {
  64913. this._color.r = meshCol[c];
  64914. this._color.g = meshCol[c + 1];
  64915. this._color.b = meshCol[c + 2];
  64916. this._color.a = meshCol[c + 3];
  64917. }
  64918. else {
  64919. this._color.r = 1.0;
  64920. this._color.g = 1.0;
  64921. this._color.b = 1.0;
  64922. this._color.a = 1.0;
  64923. }
  64924. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64925. c += 4;
  64926. if (!this.recomputeNormals && meshNor) {
  64927. this._normal.x = meshNor[n];
  64928. this._normal.y = meshNor[n + 1];
  64929. this._normal.z = meshNor[n + 2];
  64930. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64931. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64932. n += 3;
  64933. }
  64934. }
  64935. for (i = 0; i < meshInd.length; i++) {
  64936. var current_ind = p + meshInd[i];
  64937. indices.push(current_ind);
  64938. if (current_ind > 65535) {
  64939. this._needs32Bits = true;
  64940. }
  64941. }
  64942. if (this._pickable) {
  64943. var nbfaces = meshInd.length / 3;
  64944. for (i = 0; i < nbfaces; i++) {
  64945. this.pickedParticles.push({ idx: idx, faceId: i });
  64946. }
  64947. }
  64948. if (this._depthSort) {
  64949. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64950. }
  64951. return this._copy;
  64952. };
  64953. // returns a shape array from positions array
  64954. SolidParticleSystem.prototype._posToShape = function (positions) {
  64955. var shape = [];
  64956. for (var i = 0; i < positions.length; i += 3) {
  64957. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64958. }
  64959. return shape;
  64960. };
  64961. // returns a shapeUV array from a Vector4 uvs
  64962. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64963. var shapeUV = [];
  64964. if (uvs) {
  64965. for (var i = 0; i < uvs.length; i++)
  64966. shapeUV.push(uvs[i]);
  64967. }
  64968. return shapeUV;
  64969. };
  64970. // adds a new particle object in the particles array
  64971. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64972. if (bInfo === void 0) { bInfo = null; }
  64973. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64974. this.particles.push(sp);
  64975. return sp;
  64976. };
  64977. /**
  64978. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64979. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64980. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64981. * @param nb (positive integer) the number of particles to be created from this model
  64982. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64983. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64984. * @returns the number of shapes in the system
  64985. */
  64986. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64987. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64988. var meshInd = mesh.getIndices();
  64989. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64990. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64991. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64992. var bbInfo;
  64993. if (this._particlesIntersect) {
  64994. bbInfo = mesh.getBoundingInfo();
  64995. }
  64996. var shape = this._posToShape(meshPos);
  64997. var shapeUV = this._uvsToShapeUV(meshUV);
  64998. var posfunc = options ? options.positionFunction : null;
  64999. var vtxfunc = options ? options.vertexFunction : null;
  65000. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  65001. // particles
  65002. var sp;
  65003. var currentCopy;
  65004. var idx = this.nbParticles;
  65005. for (var i = 0; i < nb; i++) {
  65006. var currentPos = this._positions.length;
  65007. var currentInd = this._indices.length;
  65008. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  65009. if (this._updatable) {
  65010. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  65011. sp.position.copyFrom(currentCopy.position);
  65012. sp.rotation.copyFrom(currentCopy.rotation);
  65013. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  65014. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  65015. }
  65016. if (currentCopy.color && sp.color) {
  65017. sp.color.copyFrom(currentCopy.color);
  65018. }
  65019. sp.scaling.copyFrom(currentCopy.scaling);
  65020. sp.uvs.copyFrom(currentCopy.uvs);
  65021. }
  65022. this._index += shape.length;
  65023. idx++;
  65024. }
  65025. this.nbParticles += nb;
  65026. this._shapeCounter++;
  65027. return this._shapeCounter - 1;
  65028. };
  65029. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  65030. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  65031. this._resetCopy();
  65032. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  65033. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  65034. }
  65035. if (this._copy.rotationQuaternion) {
  65036. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  65037. }
  65038. else {
  65039. this._yaw = this._copy.rotation.y;
  65040. this._pitch = this._copy.rotation.x;
  65041. this._roll = this._copy.rotation.z;
  65042. this._quaternionRotationYPR();
  65043. }
  65044. this._quaternionToRotationMatrix();
  65045. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65046. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65047. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65048. if (this._copy.translateFromPivot) {
  65049. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  65050. }
  65051. else {
  65052. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  65053. }
  65054. this._shape = particle._model._shape;
  65055. for (var pt = 0; pt < this._shape.length; pt++) {
  65056. this._vertex.x = this._shape[pt].x;
  65057. this._vertex.y = this._shape[pt].y;
  65058. this._vertex.z = this._shape[pt].z;
  65059. if (particle._model._vertexFunction) {
  65060. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  65061. }
  65062. this._vertex.x *= this._copy.scaling.x;
  65063. this._vertex.y *= this._copy.scaling.y;
  65064. this._vertex.z *= this._copy.scaling.z;
  65065. this._vertex.x -= this._scaledPivot.x;
  65066. this._vertex.y -= this._scaledPivot.y;
  65067. this._vertex.z -= this._scaledPivot.z;
  65068. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  65069. this._rotated.addInPlace(this._pivotBackTranslation);
  65070. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  65071. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  65072. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  65073. }
  65074. particle.position.x = 0.0;
  65075. particle.position.y = 0.0;
  65076. particle.position.z = 0.0;
  65077. particle.rotation.x = 0.0;
  65078. particle.rotation.y = 0.0;
  65079. particle.rotation.z = 0.0;
  65080. particle.rotationQuaternion = null;
  65081. particle.scaling.x = 1.0;
  65082. particle.scaling.y = 1.0;
  65083. particle.scaling.z = 1.0;
  65084. particle.uvs.x = 0.0;
  65085. particle.uvs.y = 0.0;
  65086. particle.uvs.z = 1.0;
  65087. particle.uvs.w = 1.0;
  65088. particle.pivot.x = 0.0;
  65089. particle.pivot.y = 0.0;
  65090. particle.pivot.z = 0.0;
  65091. particle.translateFromPivot = false;
  65092. particle.parentId = null;
  65093. };
  65094. /**
  65095. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  65096. * @returns the SPS.
  65097. */
  65098. SolidParticleSystem.prototype.rebuildMesh = function () {
  65099. for (var p = 0; p < this.particles.length; p++) {
  65100. this._rebuildParticle(this.particles[p]);
  65101. }
  65102. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65103. return this;
  65104. };
  65105. /**
  65106. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  65107. * This method calls `updateParticle()` for each particle of the SPS.
  65108. * For an animated SPS, it is usually called within the render loop.
  65109. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  65110. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  65111. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  65112. * @returns the SPS.
  65113. */
  65114. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  65115. if (start === void 0) { start = 0; }
  65116. if (end === void 0) { end = this.nbParticles - 1; }
  65117. if (update === void 0) { update = true; }
  65118. if (!this._updatable) {
  65119. return this;
  65120. }
  65121. // custom beforeUpdate
  65122. this.beforeUpdateParticles(start, end, update);
  65123. this._cam_axisX.x = 1.0;
  65124. this._cam_axisX.y = 0.0;
  65125. this._cam_axisX.z = 0.0;
  65126. this._cam_axisY.x = 0.0;
  65127. this._cam_axisY.y = 1.0;
  65128. this._cam_axisY.z = 0.0;
  65129. this._cam_axisZ.x = 0.0;
  65130. this._cam_axisZ.y = 0.0;
  65131. this._cam_axisZ.z = 1.0;
  65132. // cases when the World Matrix is to be computed first
  65133. if (this.billboard || this._depthSort) {
  65134. this.mesh.computeWorldMatrix(true);
  65135. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  65136. }
  65137. // if the particles will always face the camera
  65138. if (this.billboard) {
  65139. // compute the camera position and un-rotate it by the current mesh rotation
  65140. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  65141. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  65142. this._cam_axisZ.normalize();
  65143. // same for camera up vector extracted from the cam view matrix
  65144. var view = this._camera.getViewMatrix(true);
  65145. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  65146. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  65147. this._cam_axisY.normalize();
  65148. this._cam_axisX.normalize();
  65149. }
  65150. // if depthSort, compute the camera global position in the mesh local system
  65151. if (this._depthSort) {
  65152. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  65153. }
  65154. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  65155. var idx = 0; // current position index in the global array positions32
  65156. var index = 0; // position start index in the global array positions32 of the current particle
  65157. var colidx = 0; // current color index in the global array colors32
  65158. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  65159. var uvidx = 0; // current uv index in the global array uvs32
  65160. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  65161. var pt = 0; // current index in the particle model shape
  65162. if (this.mesh.isFacetDataEnabled) {
  65163. this._computeBoundingBox = true;
  65164. }
  65165. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  65166. if (this._computeBoundingBox) {
  65167. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  65168. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  65169. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  65170. }
  65171. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  65172. if (this.mesh._boundingInfo) {
  65173. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  65174. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  65175. }
  65176. }
  65177. }
  65178. // particle loop
  65179. index = this.particles[start]._pos;
  65180. var vpos = (index / 3) | 0;
  65181. colorIndex = vpos * 4;
  65182. uvIndex = vpos * 2;
  65183. for (var p = start; p <= end; p++) {
  65184. this._particle = this.particles[p];
  65185. this._shape = this._particle._model._shape;
  65186. this._shapeUV = this._particle._model._shapeUV;
  65187. // call to custom user function to update the particle properties
  65188. this.updateParticle(this._particle);
  65189. // camera-particle distance for depth sorting
  65190. if (this._depthSort && this._depthSortParticles) {
  65191. var dsp = this.depthSortedParticles[p];
  65192. dsp.ind = this._particle._ind;
  65193. dsp.indicesLength = this._particle._model._indicesLength;
  65194. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  65195. }
  65196. // skip the computations for inactive or already invisible particles
  65197. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  65198. // increment indexes for the next particle
  65199. pt = this._shape.length;
  65200. index += pt * 3;
  65201. colorIndex += pt * 4;
  65202. uvIndex += pt * 2;
  65203. continue;
  65204. }
  65205. if (this._particle.isVisible) {
  65206. this._particle._stillInvisible = false; // un-mark permanent invisibility
  65207. this._particleHasParent = (this._particle.parentId !== null);
  65208. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  65209. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  65210. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  65211. // particle rotation matrix
  65212. if (this.billboard) {
  65213. this._particle.rotation.x = 0.0;
  65214. this._particle.rotation.y = 0.0;
  65215. }
  65216. if (this._computeParticleRotation || this.billboard) {
  65217. if (this._particle.rotationQuaternion) {
  65218. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65219. }
  65220. else {
  65221. this._yaw = this._particle.rotation.y;
  65222. this._pitch = this._particle.rotation.x;
  65223. this._roll = this._particle.rotation.z;
  65224. this._quaternionRotationYPR();
  65225. }
  65226. this._quaternionToRotationMatrix();
  65227. }
  65228. if (this._particleHasParent) {
  65229. this._parent = this.particles[this._particle.parentId];
  65230. 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];
  65231. 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];
  65232. 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];
  65233. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  65234. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  65235. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  65236. if (this._computeParticleRotation || this.billboard) {
  65237. 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];
  65238. 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];
  65239. 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];
  65240. 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];
  65241. 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];
  65242. 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];
  65243. 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];
  65244. 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];
  65245. 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];
  65246. }
  65247. }
  65248. else {
  65249. this._particle._globalPosition.x = this._particle.position.x;
  65250. this._particle._globalPosition.y = this._particle.position.y;
  65251. this._particle._globalPosition.z = this._particle.position.z;
  65252. if (this._computeParticleRotation || this.billboard) {
  65253. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  65254. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  65255. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  65256. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  65257. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  65258. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  65259. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  65260. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  65261. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  65262. }
  65263. }
  65264. if (this._particle.translateFromPivot) {
  65265. this._pivotBackTranslation.x = 0.0;
  65266. this._pivotBackTranslation.y = 0.0;
  65267. this._pivotBackTranslation.z = 0.0;
  65268. }
  65269. else {
  65270. this._pivotBackTranslation.x = this._scaledPivot.x;
  65271. this._pivotBackTranslation.y = this._scaledPivot.y;
  65272. this._pivotBackTranslation.z = this._scaledPivot.z;
  65273. }
  65274. // particle vertex loop
  65275. for (pt = 0; pt < this._shape.length; pt++) {
  65276. idx = index + pt * 3;
  65277. colidx = colorIndex + pt * 4;
  65278. uvidx = uvIndex + pt * 2;
  65279. this._vertex.x = this._shape[pt].x;
  65280. this._vertex.y = this._shape[pt].y;
  65281. this._vertex.z = this._shape[pt].z;
  65282. if (this._computeParticleVertex) {
  65283. this.updateParticleVertex(this._particle, this._vertex, pt);
  65284. }
  65285. // positions
  65286. this._vertex.x *= this._particle.scaling.x;
  65287. this._vertex.y *= this._particle.scaling.y;
  65288. this._vertex.z *= this._particle.scaling.z;
  65289. this._vertex.x -= this._scaledPivot.x;
  65290. this._vertex.y -= this._scaledPivot.y;
  65291. this._vertex.z -= this._scaledPivot.z;
  65292. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65293. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65294. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65295. this._rotated.x += this._pivotBackTranslation.x;
  65296. this._rotated.y += this._pivotBackTranslation.y;
  65297. this._rotated.z += this._pivotBackTranslation.z;
  65298. 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;
  65299. 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;
  65300. 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;
  65301. if (this._computeBoundingBox) {
  65302. if (this._positions32[idx] < this._minimum.x) {
  65303. this._minimum.x = this._positions32[idx];
  65304. }
  65305. if (this._positions32[idx] > this._maximum.x) {
  65306. this._maximum.x = this._positions32[idx];
  65307. }
  65308. if (this._positions32[idx + 1] < this._minimum.y) {
  65309. this._minimum.y = this._positions32[idx + 1];
  65310. }
  65311. if (this._positions32[idx + 1] > this._maximum.y) {
  65312. this._maximum.y = this._positions32[idx + 1];
  65313. }
  65314. if (this._positions32[idx + 2] < this._minimum.z) {
  65315. this._minimum.z = this._positions32[idx + 2];
  65316. }
  65317. if (this._positions32[idx + 2] > this._maximum.z) {
  65318. this._maximum.z = this._positions32[idx + 2];
  65319. }
  65320. }
  65321. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  65322. if (!this._computeParticleVertex) {
  65323. this._normal.x = this._fixedNormal32[idx];
  65324. this._normal.y = this._fixedNormal32[idx + 1];
  65325. this._normal.z = this._fixedNormal32[idx + 2];
  65326. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  65327. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  65328. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  65329. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  65330. 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;
  65331. 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;
  65332. }
  65333. if (this._computeParticleColor && this._particle.color) {
  65334. this._colors32[colidx] = this._particle.color.r;
  65335. this._colors32[colidx + 1] = this._particle.color.g;
  65336. this._colors32[colidx + 2] = this._particle.color.b;
  65337. this._colors32[colidx + 3] = this._particle.color.a;
  65338. }
  65339. if (this._computeParticleTexture) {
  65340. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65341. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65342. }
  65343. }
  65344. }
  65345. // particle just set invisible : scaled to zero and positioned at the origin
  65346. else {
  65347. this._particle._stillInvisible = true; // mark the particle as invisible
  65348. for (pt = 0; pt < this._shape.length; pt++) {
  65349. idx = index + pt * 3;
  65350. colidx = colorIndex + pt * 4;
  65351. uvidx = uvIndex + pt * 2;
  65352. this._positions32[idx] = 0.0;
  65353. this._positions32[idx + 1] = 0.0;
  65354. this._positions32[idx + 2] = 0.0;
  65355. this._normals32[idx] = 0.0;
  65356. this._normals32[idx + 1] = 0.0;
  65357. this._normals32[idx + 2] = 0.0;
  65358. if (this._computeParticleColor && this._particle.color) {
  65359. this._colors32[colidx] = this._particle.color.r;
  65360. this._colors32[colidx + 1] = this._particle.color.g;
  65361. this._colors32[colidx + 2] = this._particle.color.b;
  65362. this._colors32[colidx + 3] = this._particle.color.a;
  65363. }
  65364. if (this._computeParticleTexture) {
  65365. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  65366. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  65367. }
  65368. }
  65369. }
  65370. // if the particle intersections must be computed : update the bbInfo
  65371. if (this._particlesIntersect) {
  65372. var bInfo = this._particle._boundingInfo;
  65373. var bBox = bInfo.boundingBox;
  65374. var bSphere = bInfo.boundingSphere;
  65375. if (!this._bSphereOnly) {
  65376. // place, scale and rotate the particle bbox within the SPS local system, then update it
  65377. for (var b = 0; b < bBox.vectors.length; b++) {
  65378. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  65379. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  65380. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  65381. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  65382. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  65383. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  65384. 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;
  65385. 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;
  65386. 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;
  65387. }
  65388. bBox._update(this.mesh._worldMatrix);
  65389. }
  65390. // place and scale the particle bouding sphere in the SPS local system, then update it
  65391. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  65392. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  65393. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  65394. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  65395. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  65396. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  65397. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  65398. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  65399. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  65400. 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));
  65401. bSphere._update(this.mesh._worldMatrix);
  65402. }
  65403. // increment indexes for the next particle
  65404. index = idx + 3;
  65405. colorIndex = colidx + 4;
  65406. uvIndex = uvidx + 2;
  65407. }
  65408. // if the VBO must be updated
  65409. if (update) {
  65410. if (this._computeParticleColor) {
  65411. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  65412. }
  65413. if (this._computeParticleTexture) {
  65414. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  65415. }
  65416. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  65417. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  65418. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  65419. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  65420. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  65421. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  65422. for (var i = 0; i < this._normals32.length; i++) {
  65423. this._fixedNormal32[i] = this._normals32[i];
  65424. }
  65425. }
  65426. if (!this.mesh.areNormalsFrozen) {
  65427. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  65428. }
  65429. }
  65430. if (this._depthSort && this._depthSortParticles) {
  65431. this.depthSortedParticles.sort(this._depthSortFunction);
  65432. var dspl = this.depthSortedParticles.length;
  65433. var sorted = 0;
  65434. var lind = 0;
  65435. var sind = 0;
  65436. var sid = 0;
  65437. for (sorted = 0; sorted < dspl; sorted++) {
  65438. lind = this.depthSortedParticles[sorted].indicesLength;
  65439. sind = this.depthSortedParticles[sorted].ind;
  65440. for (var i = 0; i < lind; i++) {
  65441. this._indices32[sid] = this._indices[sind + i];
  65442. sid++;
  65443. }
  65444. }
  65445. this.mesh.updateIndices(this._indices32);
  65446. }
  65447. }
  65448. if (this._computeBoundingBox) {
  65449. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  65450. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  65451. }
  65452. this.afterUpdateParticles(start, end, update);
  65453. return this;
  65454. };
  65455. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  65456. this._halfroll = this._roll * 0.5;
  65457. this._halfpitch = this._pitch * 0.5;
  65458. this._halfyaw = this._yaw * 0.5;
  65459. this._sinRoll = Math.sin(this._halfroll);
  65460. this._cosRoll = Math.cos(this._halfroll);
  65461. this._sinPitch = Math.sin(this._halfpitch);
  65462. this._cosPitch = Math.cos(this._halfpitch);
  65463. this._sinYaw = Math.sin(this._halfyaw);
  65464. this._cosYaw = Math.cos(this._halfyaw);
  65465. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  65466. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  65467. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  65468. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  65469. };
  65470. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  65471. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  65472. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  65473. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  65474. this._rotMatrix.m[3] = 0;
  65475. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  65476. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  65477. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  65478. this._rotMatrix.m[7] = 0;
  65479. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  65480. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  65481. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  65482. this._rotMatrix.m[11] = 0;
  65483. this._rotMatrix.m[12] = 0;
  65484. this._rotMatrix.m[13] = 0;
  65485. this._rotMatrix.m[14] = 0;
  65486. this._rotMatrix.m[15] = 1.0;
  65487. };
  65488. /**
  65489. * Disposes the SPS.
  65490. */
  65491. SolidParticleSystem.prototype.dispose = function () {
  65492. this.mesh.dispose();
  65493. this.vars = null;
  65494. // drop references to internal big arrays for the GC
  65495. this._positions = null;
  65496. this._indices = null;
  65497. this._normals = null;
  65498. this._uvs = null;
  65499. this._colors = null;
  65500. this._indices32 = null;
  65501. this._positions32 = null;
  65502. this._normals32 = null;
  65503. this._fixedNormal32 = null;
  65504. this._uvs32 = null;
  65505. this._colors32 = null;
  65506. this.pickedParticles = null;
  65507. };
  65508. /**
  65509. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  65510. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65511. * @returns the SPS.
  65512. */
  65513. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  65514. if (!this._isVisibilityBoxLocked) {
  65515. this.mesh.refreshBoundingInfo();
  65516. }
  65517. return this;
  65518. };
  65519. /**
  65520. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65521. * @param size the size (float) of the visibility box
  65522. * note : this doesn't lock the SPS mesh bounding box.
  65523. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65524. */
  65525. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65526. var vis = size / 2;
  65527. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65528. };
  65529. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65530. /**
  65531. * Gets whether the SPS as always visible or not
  65532. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65533. */
  65534. get: function () {
  65535. return this._alwaysVisible;
  65536. },
  65537. /**
  65538. * Sets the SPS as always visible or not
  65539. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65540. */
  65541. set: function (val) {
  65542. this._alwaysVisible = val;
  65543. this.mesh.alwaysSelectAsActiveMesh = val;
  65544. },
  65545. enumerable: true,
  65546. configurable: true
  65547. });
  65548. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65549. /**
  65550. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65551. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65552. */
  65553. get: function () {
  65554. return this._isVisibilityBoxLocked;
  65555. },
  65556. /**
  65557. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65558. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65559. */
  65560. set: function (val) {
  65561. this._isVisibilityBoxLocked = val;
  65562. var boundingInfo = this.mesh.getBoundingInfo();
  65563. boundingInfo.isLocked = val;
  65564. },
  65565. enumerable: true,
  65566. configurable: true
  65567. });
  65568. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65569. /**
  65570. * Gets if `setParticles()` computes the particle rotations or not.
  65571. * Default value : true. The SPS is faster when it's set to false.
  65572. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65573. */
  65574. get: function () {
  65575. return this._computeParticleRotation;
  65576. },
  65577. /**
  65578. * Tells to `setParticles()` to compute the particle rotations or not.
  65579. * Default value : true. The SPS is faster when it's set to false.
  65580. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65581. */
  65582. set: function (val) {
  65583. this._computeParticleRotation = val;
  65584. },
  65585. enumerable: true,
  65586. configurable: true
  65587. });
  65588. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65589. /**
  65590. * Gets if `setParticles()` computes the particle colors or not.
  65591. * Default value : true. The SPS is faster when it's set to false.
  65592. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65593. */
  65594. get: function () {
  65595. return this._computeParticleColor;
  65596. },
  65597. /**
  65598. * Tells to `setParticles()` to compute the particle colors or not.
  65599. * Default value : true. The SPS is faster when it's set to false.
  65600. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65601. */
  65602. set: function (val) {
  65603. this._computeParticleColor = val;
  65604. },
  65605. enumerable: true,
  65606. configurable: true
  65607. });
  65608. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65609. /**
  65610. * Gets if `setParticles()` computes the particle textures or not.
  65611. * Default value : true. The SPS is faster when it's set to false.
  65612. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65613. */
  65614. get: function () {
  65615. return this._computeParticleTexture;
  65616. },
  65617. set: function (val) {
  65618. this._computeParticleTexture = val;
  65619. },
  65620. enumerable: true,
  65621. configurable: true
  65622. });
  65623. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65624. /**
  65625. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65626. * Default value : false. The SPS is faster when it's set to false.
  65627. * Note : the particle custom vertex positions aren't stored values.
  65628. */
  65629. get: function () {
  65630. return this._computeParticleVertex;
  65631. },
  65632. /**
  65633. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65634. * Default value : false. The SPS is faster when it's set to false.
  65635. * Note : the particle custom vertex positions aren't stored values.
  65636. */
  65637. set: function (val) {
  65638. this._computeParticleVertex = val;
  65639. },
  65640. enumerable: true,
  65641. configurable: true
  65642. });
  65643. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65644. /**
  65645. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65646. */
  65647. get: function () {
  65648. return this._computeBoundingBox;
  65649. },
  65650. /**
  65651. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65652. */
  65653. set: function (val) {
  65654. this._computeBoundingBox = val;
  65655. },
  65656. enumerable: true,
  65657. configurable: true
  65658. });
  65659. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65660. /**
  65661. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65662. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65663. * Default : `true`
  65664. */
  65665. get: function () {
  65666. return this._depthSortParticles;
  65667. },
  65668. /**
  65669. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65670. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65671. * Default : `true`
  65672. */
  65673. set: function (val) {
  65674. this._depthSortParticles = val;
  65675. },
  65676. enumerable: true,
  65677. configurable: true
  65678. });
  65679. // =======================================================================
  65680. // Particle behavior logic
  65681. // these following methods may be overwritten by the user to fit his needs
  65682. /**
  65683. * This function does nothing. It may be overwritten to set all the particle first values.
  65684. * The SPS doesn't call this function, you may have to call it by your own.
  65685. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65686. */
  65687. SolidParticleSystem.prototype.initParticles = function () {
  65688. };
  65689. /**
  65690. * This function does nothing. It may be overwritten to recycle a particle.
  65691. * The SPS doesn't call this function, you may have to call it by your own.
  65692. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65693. * @param particle The particle to recycle
  65694. * @returns the recycled particle
  65695. */
  65696. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65697. return particle;
  65698. };
  65699. /**
  65700. * Updates a particle : this function should be overwritten by the user.
  65701. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65702. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65703. * @example : just set a particle position or velocity and recycle conditions
  65704. * @param particle The particle to update
  65705. * @returns the updated particle
  65706. */
  65707. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65708. return particle;
  65709. };
  65710. /**
  65711. * Updates a vertex of a particle : it can be overwritten by the user.
  65712. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65713. * @param particle the current particle
  65714. * @param vertex the current index of the current particle
  65715. * @param pt the index of the current vertex in the particle shape
  65716. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65717. * @example : just set a vertex particle position
  65718. * @returns the updated vertex
  65719. */
  65720. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65721. return vertex;
  65722. };
  65723. /**
  65724. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65725. * This does nothing and may be overwritten by the user.
  65726. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65727. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65728. * @param update the boolean update value actually passed to setParticles()
  65729. */
  65730. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65731. };
  65732. /**
  65733. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65734. * This will be passed three parameters.
  65735. * This does nothing and may be overwritten by the user.
  65736. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65737. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65738. * @param update the boolean update value actually passed to setParticles()
  65739. */
  65740. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65741. };
  65742. return SolidParticleSystem;
  65743. }());
  65744. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65745. })(BABYLON || (BABYLON = {}));
  65746. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65747. var BABYLON;
  65748. (function (BABYLON) {
  65749. /**
  65750. * Class containing static functions to help procedurally build meshes
  65751. */
  65752. var MeshBuilder = /** @class */ (function () {
  65753. function MeshBuilder() {
  65754. }
  65755. MeshBuilder.updateSideOrientation = function (orientation) {
  65756. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65757. return BABYLON.Mesh.DOUBLESIDE;
  65758. }
  65759. if (orientation === undefined || orientation === null) {
  65760. return BABYLON.Mesh.FRONTSIDE;
  65761. }
  65762. return orientation;
  65763. };
  65764. /**
  65765. * Creates a box mesh
  65766. * * The parameter `size` sets the size (float) of each box side (default 1)
  65767. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  65768. * * 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)
  65769. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65770. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65771. * * 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
  65772. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65773. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65774. * @param name defines the name of the mesh
  65775. * @param options defines the options used to create the mesh
  65776. * @param scene defines the hosting scene
  65777. * @returns the box mesh
  65778. */
  65779. MeshBuilder.CreateBox = function (name, options, scene) {
  65780. if (scene === void 0) { scene = null; }
  65781. var box = new BABYLON.Mesh(name, scene);
  65782. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65783. box._originalBuilderSideOrientation = options.sideOrientation;
  65784. var vertexData = BABYLON.VertexData.CreateBox(options);
  65785. vertexData.applyToMesh(box, options.updatable);
  65786. return box;
  65787. };
  65788. /**
  65789. * Creates a sphere mesh
  65790. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65791. * * 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`)
  65792. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65793. * * 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
  65794. * * 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)
  65795. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65796. * * 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
  65797. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65798. * @param name defines the name of the mesh
  65799. * @param options defines the options used to create the mesh
  65800. * @param scene defines the hosting scene
  65801. * @returns the sphere mesh
  65802. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65803. */
  65804. MeshBuilder.CreateSphere = function (name, options, scene) {
  65805. var sphere = new BABYLON.Mesh(name, scene);
  65806. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65807. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65808. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65809. vertexData.applyToMesh(sphere, options.updatable);
  65810. return sphere;
  65811. };
  65812. /**
  65813. * Creates a plane polygonal mesh. By default, this is a disc
  65814. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65815. * * 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
  65816. * * 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
  65817. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65818. * * 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
  65819. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65820. * @param name defines the name of the mesh
  65821. * @param options defines the options used to create the mesh
  65822. * @param scene defines the hosting scene
  65823. * @returns the plane polygonal mesh
  65824. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65825. */
  65826. MeshBuilder.CreateDisc = function (name, options, scene) {
  65827. if (scene === void 0) { scene = null; }
  65828. var disc = new BABYLON.Mesh(name, scene);
  65829. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65830. disc._originalBuilderSideOrientation = options.sideOrientation;
  65831. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65832. vertexData.applyToMesh(disc, options.updatable);
  65833. return disc;
  65834. };
  65835. /**
  65836. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65837. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65838. * * 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`)
  65839. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65840. * * 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
  65841. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65842. * * 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
  65843. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65844. * @param name defines the name of the mesh
  65845. * @param options defines the options used to create the mesh
  65846. * @param scene defines the hosting scene
  65847. * @returns the icosahedron mesh
  65848. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65849. */
  65850. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65851. var sphere = new BABYLON.Mesh(name, scene);
  65852. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65853. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65854. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65855. vertexData.applyToMesh(sphere, options.updatable);
  65856. return sphere;
  65857. };
  65858. ;
  65859. /**
  65860. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65861. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65862. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65863. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65864. * * 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
  65865. * * 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
  65866. * * 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
  65867. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65868. * * 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
  65869. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65870. * * 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
  65871. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65872. * * 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
  65873. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65874. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65875. * @param name defines the name of the mesh
  65876. * @param options defines the options used to create the mesh
  65877. * @param scene defines the hosting scene
  65878. * @returns the ribbon mesh
  65879. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65880. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65881. */
  65882. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65883. if (scene === void 0) { scene = null; }
  65884. var pathArray = options.pathArray;
  65885. var closeArray = options.closeArray;
  65886. var closePath = options.closePath;
  65887. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65888. var instance = options.instance;
  65889. var updatable = options.updatable;
  65890. if (instance) { // existing ribbon instance update
  65891. // positionFunction : ribbon case
  65892. // only pathArray and sideOrientation parameters are taken into account for positions update
  65893. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65894. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65895. var positionFunction = function (positions) {
  65896. var minlg = pathArray[0].length;
  65897. var i = 0;
  65898. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65899. for (var si = 1; si <= ns; si++) {
  65900. for (var p = 0; p < pathArray.length; p++) {
  65901. var path = pathArray[p];
  65902. var l = path.length;
  65903. minlg = (minlg < l) ? minlg : l;
  65904. var j = 0;
  65905. while (j < minlg) {
  65906. positions[i] = path[j].x;
  65907. positions[i + 1] = path[j].y;
  65908. positions[i + 2] = path[j].z;
  65909. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65910. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65911. }
  65912. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65913. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65914. }
  65915. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65916. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65917. }
  65918. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65919. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65920. }
  65921. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65922. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65923. }
  65924. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65925. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65926. }
  65927. j++;
  65928. i += 3;
  65929. }
  65930. if (instance._closePath) {
  65931. positions[i] = path[0].x;
  65932. positions[i + 1] = path[0].y;
  65933. positions[i + 2] = path[0].z;
  65934. i += 3;
  65935. }
  65936. }
  65937. }
  65938. };
  65939. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65940. positionFunction(positions);
  65941. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65942. instance._boundingInfo.update(instance._worldMatrix);
  65943. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65944. if (options.colors) {
  65945. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65946. for (var c = 0; c < options.colors.length; c++) {
  65947. colors[c * 4] = options.colors[c].r;
  65948. colors[c * 4 + 1] = options.colors[c].g;
  65949. colors[c * 4 + 2] = options.colors[c].b;
  65950. colors[c * 4 + 3] = options.colors[c].a;
  65951. }
  65952. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65953. }
  65954. if (options.uvs) {
  65955. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65956. for (var i = 0; i < options.uvs.length; i++) {
  65957. uvs[i * 2] = options.uvs[i].x;
  65958. uvs[i * 2 + 1] = options.uvs[i].y;
  65959. }
  65960. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65961. }
  65962. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65963. var indices = instance.getIndices();
  65964. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65965. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65966. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65967. if (instance._closePath) {
  65968. var indexFirst = 0;
  65969. var indexLast = 0;
  65970. for (var p = 0; p < pathArray.length; p++) {
  65971. indexFirst = instance._idx[p] * 3;
  65972. if (p + 1 < pathArray.length) {
  65973. indexLast = (instance._idx[p + 1] - 1) * 3;
  65974. }
  65975. else {
  65976. indexLast = normals.length - 3;
  65977. }
  65978. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65979. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65980. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65981. normals[indexLast] = normals[indexFirst];
  65982. normals[indexLast + 1] = normals[indexFirst + 1];
  65983. normals[indexLast + 2] = normals[indexFirst + 2];
  65984. }
  65985. }
  65986. if (!(instance.areNormalsFrozen)) {
  65987. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65988. }
  65989. }
  65990. return instance;
  65991. }
  65992. else { // new ribbon creation
  65993. var ribbon = new BABYLON.Mesh(name, scene);
  65994. ribbon._originalBuilderSideOrientation = sideOrientation;
  65995. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65996. if (closePath) {
  65997. ribbon._idx = vertexData._idx;
  65998. }
  65999. ribbon._closePath = closePath;
  66000. ribbon._closeArray = closeArray;
  66001. vertexData.applyToMesh(ribbon, updatable);
  66002. return ribbon;
  66003. }
  66004. };
  66005. /**
  66006. * Creates a cylinder or a cone mesh
  66007. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  66008. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  66009. * * 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.
  66010. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  66011. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  66012. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  66013. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  66014. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  66015. * * 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).
  66016. * * 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
  66017. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  66018. * * 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
  66019. * * 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.
  66020. * * If `enclose` is false, a ring surface is one element.
  66021. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  66022. * * 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
  66023. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66024. * * 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
  66025. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66026. * @param name defines the name of the mesh
  66027. * @param options defines the options used to create the mesh
  66028. * @param scene defines the hosting scene
  66029. * @returns the cylinder mesh
  66030. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  66031. */
  66032. MeshBuilder.CreateCylinder = function (name, options, scene) {
  66033. var cylinder = new BABYLON.Mesh(name, scene);
  66034. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66035. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  66036. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  66037. vertexData.applyToMesh(cylinder, options.updatable);
  66038. return cylinder;
  66039. };
  66040. /**
  66041. * Creates a torus mesh
  66042. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  66043. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  66044. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  66045. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66046. * * 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
  66047. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66048. * @param name defines the name of the mesh
  66049. * @param options defines the options used to create the mesh
  66050. * @param scene defines the hosting scene
  66051. * @returns the torus mesh
  66052. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  66053. */
  66054. MeshBuilder.CreateTorus = function (name, options, scene) {
  66055. var torus = new BABYLON.Mesh(name, scene);
  66056. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66057. torus._originalBuilderSideOrientation = options.sideOrientation;
  66058. var vertexData = BABYLON.VertexData.CreateTorus(options);
  66059. vertexData.applyToMesh(torus, options.updatable);
  66060. return torus;
  66061. };
  66062. /**
  66063. * Creates a torus knot mesh
  66064. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  66065. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  66066. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  66067. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  66068. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66069. * * 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
  66070. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66071. * @param name defines the name of the mesh
  66072. * @param options defines the options used to create the mesh
  66073. * @param scene defines the hosting scene
  66074. * @returns the torus knot mesh
  66075. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  66076. */
  66077. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  66078. var torusKnot = new BABYLON.Mesh(name, scene);
  66079. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66080. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  66081. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  66082. vertexData.applyToMesh(torusKnot, options.updatable);
  66083. return torusKnot;
  66084. };
  66085. /**
  66086. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  66087. * * 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
  66088. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  66089. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  66090. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  66091. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  66092. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  66093. * * 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
  66094. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  66095. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66096. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  66097. * @param name defines the name of the new line system
  66098. * @param options defines the options used to create the line system
  66099. * @param scene defines the hosting scene
  66100. * @returns a new line system mesh
  66101. */
  66102. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  66103. var instance = options.instance;
  66104. var lines = options.lines;
  66105. var colors = options.colors;
  66106. if (instance) { // lines update
  66107. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66108. var vertexColor;
  66109. var lineColors;
  66110. if (colors) {
  66111. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66112. }
  66113. var i = 0;
  66114. var c = 0;
  66115. for (var l = 0; l < lines.length; l++) {
  66116. var points = lines[l];
  66117. for (var p = 0; p < points.length; p++) {
  66118. positions[i] = points[p].x;
  66119. positions[i + 1] = points[p].y;
  66120. positions[i + 2] = points[p].z;
  66121. if (colors && vertexColor) {
  66122. lineColors = colors[l];
  66123. vertexColor[c] = lineColors[p].r;
  66124. vertexColor[c + 1] = lineColors[p].g;
  66125. vertexColor[c + 2] = lineColors[p].b;
  66126. vertexColor[c + 3] = lineColors[p].a;
  66127. c += 4;
  66128. }
  66129. i += 3;
  66130. }
  66131. }
  66132. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  66133. if (colors && vertexColor) {
  66134. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  66135. }
  66136. return instance;
  66137. }
  66138. // line system creation
  66139. var useVertexColor = (colors) ? true : false;
  66140. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  66141. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  66142. vertexData.applyToMesh(lineSystem, options.updatable);
  66143. return lineSystem;
  66144. };
  66145. /**
  66146. * Creates a line mesh
  66147. * 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
  66148. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66149. * * The parameter `points` is an array successive Vector3
  66150. * * 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
  66151. * * The optional parameter `colors` is an array of successive Color4, one per line point
  66152. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  66153. * * When updating an instance, remember that only point positions can change, not the number of points
  66154. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66155. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  66156. * @param name defines the name of the new line system
  66157. * @param options defines the options used to create the line system
  66158. * @param scene defines the hosting scene
  66159. * @returns a new line mesh
  66160. */
  66161. MeshBuilder.CreateLines = function (name, options, scene) {
  66162. if (scene === void 0) { scene = null; }
  66163. var colors = (options.colors) ? [options.colors] : null;
  66164. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  66165. return lines;
  66166. };
  66167. /**
  66168. * Creates a dashed line mesh
  66169. * * 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
  66170. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  66171. * * The parameter `points` is an array successive Vector3
  66172. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  66173. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  66174. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  66175. * * 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
  66176. * * When updating an instance, remember that only point positions can change, not the number of points
  66177. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66178. * @param name defines the name of the mesh
  66179. * @param options defines the options used to create the mesh
  66180. * @param scene defines the hosting scene
  66181. * @returns the dashed line mesh
  66182. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  66183. */
  66184. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  66185. if (scene === void 0) { scene = null; }
  66186. var points = options.points;
  66187. var instance = options.instance;
  66188. var gapSize = options.gapSize || 1;
  66189. var dashSize = options.dashSize || 3;
  66190. if (instance) { // dashed lines update
  66191. var positionFunction = function (positions) {
  66192. var curvect = BABYLON.Vector3.Zero();
  66193. var nbSeg = positions.length / 6;
  66194. var lg = 0;
  66195. var nb = 0;
  66196. var shft = 0;
  66197. var dashshft = 0;
  66198. var curshft = 0;
  66199. var p = 0;
  66200. var i = 0;
  66201. var j = 0;
  66202. for (i = 0; i < points.length - 1; i++) {
  66203. points[i + 1].subtractToRef(points[i], curvect);
  66204. lg += curvect.length();
  66205. }
  66206. shft = lg / nbSeg;
  66207. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  66208. for (i = 0; i < points.length - 1; i++) {
  66209. points[i + 1].subtractToRef(points[i], curvect);
  66210. nb = Math.floor(curvect.length() / shft);
  66211. curvect.normalize();
  66212. j = 0;
  66213. while (j < nb && p < positions.length) {
  66214. curshft = shft * j;
  66215. positions[p] = points[i].x + curshft * curvect.x;
  66216. positions[p + 1] = points[i].y + curshft * curvect.y;
  66217. positions[p + 2] = points[i].z + curshft * curvect.z;
  66218. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  66219. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  66220. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  66221. p += 6;
  66222. j++;
  66223. }
  66224. }
  66225. while (p < positions.length) {
  66226. positions[p] = points[i].x;
  66227. positions[p + 1] = points[i].y;
  66228. positions[p + 2] = points[i].z;
  66229. p += 3;
  66230. }
  66231. };
  66232. instance.updateMeshPositions(positionFunction, false);
  66233. return instance;
  66234. }
  66235. // dashed lines creation
  66236. var dashedLines = new BABYLON.LinesMesh(name, scene);
  66237. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  66238. vertexData.applyToMesh(dashedLines, options.updatable);
  66239. dashedLines.dashSize = dashSize;
  66240. dashedLines.gapSize = gapSize;
  66241. return dashedLines;
  66242. };
  66243. /**
  66244. * 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.
  66245. * * 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.
  66246. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66247. * * 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.
  66248. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  66249. * * 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
  66250. * * 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
  66251. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  66252. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66253. * * 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
  66254. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  66255. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66256. * @param name defines the name of the mesh
  66257. * @param options defines the options used to create the mesh
  66258. * @param scene defines the hosting scene
  66259. * @returns the extruded shape mesh
  66260. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66261. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66262. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66263. */
  66264. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  66265. if (scene === void 0) { scene = null; }
  66266. var path = options.path;
  66267. var shape = options.shape;
  66268. var scale = options.scale || 1;
  66269. var rotation = options.rotation || 0;
  66270. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66271. var updatable = options.updatable;
  66272. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66273. var instance = options.instance || null;
  66274. var invertUV = options.invertUV || false;
  66275. 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);
  66276. };
  66277. /**
  66278. * Creates an custom extruded shape mesh.
  66279. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  66280. * * 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.
  66281. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  66282. * * 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
  66283. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  66284. * * 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
  66285. * * It must returns a float value that will be the scale value applied to the shape on each path point
  66286. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  66287. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  66288. * * 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
  66289. * * 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
  66290. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  66291. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66292. * * 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
  66293. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66294. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66295. * @param name defines the name of the mesh
  66296. * @param options defines the options used to create the mesh
  66297. * @param scene defines the hosting scene
  66298. * @returns the custom extruded shape mesh
  66299. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  66300. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66301. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  66302. */
  66303. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  66304. var path = options.path;
  66305. var shape = options.shape;
  66306. var scaleFunction = options.scaleFunction || (function () { return 1; });
  66307. var rotationFunction = options.rotationFunction || (function () { return 0; });
  66308. var ribbonCloseArray = options.ribbonCloseArray || false;
  66309. var ribbonClosePath = options.ribbonClosePath || false;
  66310. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  66311. var updatable = options.updatable;
  66312. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66313. var instance = options.instance;
  66314. var invertUV = options.invertUV || false;
  66315. 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);
  66316. };
  66317. /**
  66318. * Creates lathe mesh.
  66319. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  66320. * * 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
  66321. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  66322. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  66323. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  66324. * * 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
  66325. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  66326. * * 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
  66327. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66328. * * 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
  66329. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66330. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66331. * @param name defines the name of the mesh
  66332. * @param options defines the options used to create the mesh
  66333. * @param scene defines the hosting scene
  66334. * @returns the lathe mesh
  66335. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  66336. */
  66337. MeshBuilder.CreateLathe = function (name, options, scene) {
  66338. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  66339. var closed = (options.closed === undefined) ? true : options.closed;
  66340. var shape = options.shape;
  66341. var radius = options.radius || 1;
  66342. var tessellation = options.tessellation || 64;
  66343. var clip = options.clip || 0;
  66344. var updatable = options.updatable;
  66345. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66346. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66347. var pi2 = Math.PI * 2;
  66348. var paths = new Array();
  66349. var invertUV = options.invertUV || false;
  66350. var i = 0;
  66351. var p = 0;
  66352. var step = pi2 / tessellation * arc;
  66353. var rotated;
  66354. var path = new Array();
  66355. for (i = 0; i <= tessellation - clip; i++) {
  66356. var path = [];
  66357. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  66358. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  66359. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  66360. }
  66361. for (p = 0; p < shape.length; p++) {
  66362. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  66363. path.push(rotated);
  66364. }
  66365. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  66366. 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));
  66367. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  66368. }
  66369. paths.push(path);
  66370. }
  66371. // lathe ribbon
  66372. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66373. return lathe;
  66374. };
  66375. /**
  66376. * Creates a plane mesh
  66377. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  66378. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  66379. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  66380. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66381. * * 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
  66382. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66383. * @param name defines the name of the mesh
  66384. * @param options defines the options used to create the mesh
  66385. * @param scene defines the hosting scene
  66386. * @returns the plane mesh
  66387. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66388. */
  66389. MeshBuilder.CreatePlane = function (name, options, scene) {
  66390. var plane = new BABYLON.Mesh(name, scene);
  66391. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66392. plane._originalBuilderSideOrientation = options.sideOrientation;
  66393. var vertexData = BABYLON.VertexData.CreatePlane(options);
  66394. vertexData.applyToMesh(plane, options.updatable);
  66395. if (options.sourcePlane) {
  66396. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  66397. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  66398. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  66399. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  66400. plane.rotate(vectorProduct, product);
  66401. }
  66402. }
  66403. return plane;
  66404. };
  66405. /**
  66406. * Creates a ground mesh
  66407. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  66408. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  66409. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66410. * @param name defines the name of the mesh
  66411. * @param options defines the options used to create the mesh
  66412. * @param scene defines the hosting scene
  66413. * @returns the ground mesh
  66414. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  66415. */
  66416. MeshBuilder.CreateGround = function (name, options, scene) {
  66417. var ground = new BABYLON.GroundMesh(name, scene);
  66418. ground._setReady(false);
  66419. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  66420. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  66421. ground._width = options.width || 1;
  66422. ground._height = options.height || 1;
  66423. ground._maxX = ground._width / 2;
  66424. ground._maxZ = ground._height / 2;
  66425. ground._minX = -ground._maxX;
  66426. ground._minZ = -ground._maxZ;
  66427. var vertexData = BABYLON.VertexData.CreateGround(options);
  66428. vertexData.applyToMesh(ground, options.updatable);
  66429. ground._setReady(true);
  66430. return ground;
  66431. };
  66432. /**
  66433. * Creates a tiled ground mesh
  66434. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  66435. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  66436. * * 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
  66437. * * 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
  66438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66439. * @param name defines the name of the mesh
  66440. * @param options defines the options used to create the mesh
  66441. * @param scene defines the hosting scene
  66442. * @returns the tiled ground mesh
  66443. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  66444. */
  66445. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  66446. var tiledGround = new BABYLON.Mesh(name, scene);
  66447. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  66448. vertexData.applyToMesh(tiledGround, options.updatable);
  66449. return tiledGround;
  66450. };
  66451. /**
  66452. * Creates a ground mesh from a height map
  66453. * * The parameter `url` sets the URL of the height map image resource.
  66454. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  66455. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  66456. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  66457. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  66458. * * 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.
  66459. * * 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).
  66460. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  66461. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  66462. * @param name defines the name of the mesh
  66463. * @param url defines the url to the height map
  66464. * @param options defines the options used to create the mesh
  66465. * @param scene defines the hosting scene
  66466. * @returns the ground mesh
  66467. * @see http://doc.babylonjs.com/babylon101/height_map
  66468. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  66469. */
  66470. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  66471. var width = options.width || 10.0;
  66472. var height = options.height || 10.0;
  66473. var subdivisions = options.subdivisions || 1 | 0;
  66474. var minHeight = options.minHeight || 0.0;
  66475. var maxHeight = options.maxHeight || 1.0;
  66476. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  66477. var alphaFilter = options.alphaFilter || 0.0;
  66478. var updatable = options.updatable;
  66479. var onReady = options.onReady;
  66480. var ground = new BABYLON.GroundMesh(name, scene);
  66481. ground._subdivisionsX = subdivisions;
  66482. ground._subdivisionsY = subdivisions;
  66483. ground._width = width;
  66484. ground._height = height;
  66485. ground._maxX = ground._width / 2.0;
  66486. ground._maxZ = ground._height / 2.0;
  66487. ground._minX = -ground._maxX;
  66488. ground._minZ = -ground._maxZ;
  66489. ground._setReady(false);
  66490. var onload = function (img) {
  66491. // Getting height map data
  66492. var canvas = document.createElement("canvas");
  66493. var context = canvas.getContext("2d");
  66494. if (!context) {
  66495. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  66496. }
  66497. if (scene.isDisposed) {
  66498. return;
  66499. }
  66500. var bufferWidth = img.width;
  66501. var bufferHeight = img.height;
  66502. canvas.width = bufferWidth;
  66503. canvas.height = bufferHeight;
  66504. context.drawImage(img, 0, 0);
  66505. // Create VertexData from map data
  66506. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  66507. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  66508. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  66509. width: width, height: height,
  66510. subdivisions: subdivisions,
  66511. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  66512. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  66513. alphaFilter: alphaFilter
  66514. });
  66515. vertexData.applyToMesh(ground, updatable);
  66516. //execute ready callback, if set
  66517. if (onReady) {
  66518. onReady(ground);
  66519. }
  66520. ground._setReady(true);
  66521. };
  66522. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66523. return ground;
  66524. };
  66525. /**
  66526. * Creates a polygon mesh
  66527. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66528. * * 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
  66529. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66530. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66531. * * 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)
  66532. * * Remember you can only change the shape positions, not their number when updating a polygon
  66533. * @param name defines the name of the mesh
  66534. * @param options defines the options used to create the mesh
  66535. * @param scene defines the hosting scene
  66536. * @returns the polygon mesh
  66537. */
  66538. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66539. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66540. var shape = options.shape;
  66541. var holes = options.holes || [];
  66542. var depth = options.depth || 0;
  66543. var contours = [];
  66544. var hole = [];
  66545. for (var i = 0; i < shape.length; i++) {
  66546. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66547. }
  66548. var epsilon = 0.00000001;
  66549. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66550. contours.pop();
  66551. }
  66552. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66553. for (var hNb = 0; hNb < holes.length; hNb++) {
  66554. hole = [];
  66555. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66556. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66557. }
  66558. polygonTriangulation.addHole(hole);
  66559. }
  66560. var polygon = polygonTriangulation.build(options.updatable, depth);
  66561. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66562. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66563. vertexData.applyToMesh(polygon, options.updatable);
  66564. return polygon;
  66565. };
  66566. ;
  66567. /**
  66568. * Creates an extruded polygon mesh, with depth in the Y direction.
  66569. * * 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)
  66570. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66571. * @param name defines the name of the mesh
  66572. * @param options defines the options used to create the mesh
  66573. * @param scene defines the hosting scene
  66574. * @returns the polygon mesh
  66575. */
  66576. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66577. return MeshBuilder.CreatePolygon(name, options, scene);
  66578. };
  66579. ;
  66580. /**
  66581. * Creates a tube mesh.
  66582. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66583. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66584. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66585. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66586. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66587. * * 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)
  66588. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66589. * * 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
  66590. * * 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
  66591. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66592. * * 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
  66593. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66594. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66595. * @param name defines the name of the mesh
  66596. * @param options defines the options used to create the mesh
  66597. * @param scene defines the hosting scene
  66598. * @returns the tube mesh
  66599. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66600. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66601. */
  66602. MeshBuilder.CreateTube = function (name, options, scene) {
  66603. var path = options.path;
  66604. var instance = options.instance;
  66605. var radius = 1.0;
  66606. if (instance) {
  66607. radius = instance.radius;
  66608. }
  66609. if (options.radius !== undefined) {
  66610. radius = options.radius;
  66611. }
  66612. ;
  66613. var tessellation = options.tessellation || 64 | 0;
  66614. var radiusFunction = options.radiusFunction || null;
  66615. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66616. var invertUV = options.invertUV || false;
  66617. var updatable = options.updatable;
  66618. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66619. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66620. // tube geometry
  66621. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66622. var tangents = path3D.getTangents();
  66623. var normals = path3D.getNormals();
  66624. var distances = path3D.getDistances();
  66625. var pi2 = Math.PI * 2;
  66626. var step = pi2 / tessellation * arc;
  66627. var returnRadius = function () { return radius; };
  66628. var radiusFunctionFinal = radiusFunction || returnRadius;
  66629. var circlePath;
  66630. var rad;
  66631. var normal;
  66632. var rotated;
  66633. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66634. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66635. for (var i = 0; i < path.length; i++) {
  66636. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66637. circlePath = Array(); // current circle array
  66638. normal = normals[i]; // current normal
  66639. for (var t = 0; t < tessellation; t++) {
  66640. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66641. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66642. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66643. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66644. circlePath[t] = rotated;
  66645. }
  66646. circlePaths[index] = circlePath;
  66647. index++;
  66648. }
  66649. // cap
  66650. var capPath = function (nbPoints, pathIndex) {
  66651. var pointCap = Array();
  66652. for (var i = 0; i < nbPoints; i++) {
  66653. pointCap.push(path[pathIndex]);
  66654. }
  66655. return pointCap;
  66656. };
  66657. switch (cap) {
  66658. case BABYLON.Mesh.NO_CAP:
  66659. break;
  66660. case BABYLON.Mesh.CAP_START:
  66661. circlePaths[0] = capPath(tessellation, 0);
  66662. circlePaths[1] = circlePaths[2].slice(0);
  66663. break;
  66664. case BABYLON.Mesh.CAP_END:
  66665. circlePaths[index] = circlePaths[index - 1].slice(0);
  66666. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66667. break;
  66668. case BABYLON.Mesh.CAP_ALL:
  66669. circlePaths[0] = capPath(tessellation, 0);
  66670. circlePaths[1] = circlePaths[2].slice(0);
  66671. circlePaths[index] = circlePaths[index - 1].slice(0);
  66672. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66673. break;
  66674. default:
  66675. break;
  66676. }
  66677. return circlePaths;
  66678. };
  66679. var path3D;
  66680. var pathArray;
  66681. if (instance) { // tube update
  66682. var arc = options.arc || instance.arc;
  66683. path3D = (instance.path3D).update(path);
  66684. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66685. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66686. instance.path3D = path3D;
  66687. instance.pathArray = pathArray;
  66688. instance.arc = arc;
  66689. instance.radius = radius;
  66690. return instance;
  66691. }
  66692. // tube creation
  66693. path3D = new BABYLON.Path3D(path);
  66694. var newPathArray = new Array();
  66695. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66696. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66697. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66698. tube.pathArray = pathArray;
  66699. tube.path3D = path3D;
  66700. tube.tessellation = tessellation;
  66701. tube.cap = cap;
  66702. tube.arc = options.arc;
  66703. tube.radius = radius;
  66704. return tube;
  66705. };
  66706. /**
  66707. * Creates a polyhedron mesh
  66708. * * 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
  66709. * * The parameter `size` (positive float, default 1) sets the polygon size
  66710. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66711. * * 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`
  66712. * * 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
  66713. * * 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)`)
  66714. * * 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
  66715. * * 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
  66716. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66717. * * 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
  66718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66719. * @param name defines the name of the mesh
  66720. * @param options defines the options used to create the mesh
  66721. * @param scene defines the hosting scene
  66722. * @returns the polyhedron mesh
  66723. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66724. */
  66725. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66726. var polyhedron = new BABYLON.Mesh(name, scene);
  66727. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66728. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66729. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66730. vertexData.applyToMesh(polyhedron, options.updatable);
  66731. return polyhedron;
  66732. };
  66733. /**
  66734. * Creates a decal mesh.
  66735. * 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
  66736. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66737. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66738. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66739. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66740. * @param name defines the name of the mesh
  66741. * @param sourceMesh defines the mesh where the decal must be applied
  66742. * @param options defines the options used to create the mesh
  66743. * @param scene defines the hosting scene
  66744. * @returns the decal mesh
  66745. * @see http://doc.babylonjs.com/how_to/decals
  66746. */
  66747. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66748. var indices = sourceMesh.getIndices();
  66749. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66750. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66751. var position = options.position || BABYLON.Vector3.Zero();
  66752. var normal = options.normal || BABYLON.Vector3.Up();
  66753. var size = options.size || BABYLON.Vector3.One();
  66754. var angle = options.angle || 0;
  66755. // Getting correct rotation
  66756. if (!normal) {
  66757. var target = new BABYLON.Vector3(0, 0, 1);
  66758. var camera = sourceMesh.getScene().activeCamera;
  66759. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66760. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66761. }
  66762. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66763. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66764. var pitch = Math.atan2(normal.y, len);
  66765. // Matrix
  66766. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66767. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66768. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66769. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66770. var vertexData = new BABYLON.VertexData();
  66771. vertexData.indices = [];
  66772. vertexData.positions = [];
  66773. vertexData.normals = [];
  66774. vertexData.uvs = [];
  66775. var currentVertexDataIndex = 0;
  66776. var extractDecalVector3 = function (indexId) {
  66777. var result = new BABYLON.PositionNormalVertex();
  66778. if (!indices || !positions || !normals) {
  66779. return result;
  66780. }
  66781. var vertexId = indices[indexId];
  66782. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66783. // Send vector to decal local world
  66784. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66785. // Get normal
  66786. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66787. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66788. return result;
  66789. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66790. var clip = function (vertices, axis) {
  66791. if (vertices.length === 0) {
  66792. return vertices;
  66793. }
  66794. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66795. var clipVertices = function (v0, v1) {
  66796. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66797. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66798. };
  66799. var result = new Array();
  66800. for (var index = 0; index < vertices.length; index += 3) {
  66801. var v1Out;
  66802. var v2Out;
  66803. var v3Out;
  66804. var total = 0;
  66805. var nV1 = null;
  66806. var nV2 = null;
  66807. var nV3 = null;
  66808. var nV4 = null;
  66809. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66810. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66811. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66812. v1Out = d1 > 0;
  66813. v2Out = d2 > 0;
  66814. v3Out = d3 > 0;
  66815. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66816. switch (total) {
  66817. case 0:
  66818. result.push(vertices[index]);
  66819. result.push(vertices[index + 1]);
  66820. result.push(vertices[index + 2]);
  66821. break;
  66822. case 1:
  66823. if (v1Out) {
  66824. nV1 = vertices[index + 1];
  66825. nV2 = vertices[index + 2];
  66826. nV3 = clipVertices(vertices[index], nV1);
  66827. nV4 = clipVertices(vertices[index], nV2);
  66828. }
  66829. if (v2Out) {
  66830. nV1 = vertices[index];
  66831. nV2 = vertices[index + 2];
  66832. nV3 = clipVertices(vertices[index + 1], nV1);
  66833. nV4 = clipVertices(vertices[index + 1], nV2);
  66834. result.push(nV3);
  66835. result.push(nV2.clone());
  66836. result.push(nV1.clone());
  66837. result.push(nV2.clone());
  66838. result.push(nV3.clone());
  66839. result.push(nV4);
  66840. break;
  66841. }
  66842. if (v3Out) {
  66843. nV1 = vertices[index];
  66844. nV2 = vertices[index + 1];
  66845. nV3 = clipVertices(vertices[index + 2], nV1);
  66846. nV4 = clipVertices(vertices[index + 2], nV2);
  66847. }
  66848. if (nV1 && nV2 && nV3 && nV4) {
  66849. result.push(nV1.clone());
  66850. result.push(nV2.clone());
  66851. result.push(nV3);
  66852. result.push(nV4);
  66853. result.push(nV3.clone());
  66854. result.push(nV2.clone());
  66855. }
  66856. break;
  66857. case 2:
  66858. if (!v1Out) {
  66859. nV1 = vertices[index].clone();
  66860. nV2 = clipVertices(nV1, vertices[index + 1]);
  66861. nV3 = clipVertices(nV1, vertices[index + 2]);
  66862. result.push(nV1);
  66863. result.push(nV2);
  66864. result.push(nV3);
  66865. }
  66866. if (!v2Out) {
  66867. nV1 = vertices[index + 1].clone();
  66868. nV2 = clipVertices(nV1, vertices[index + 2]);
  66869. nV3 = clipVertices(nV1, vertices[index]);
  66870. result.push(nV1);
  66871. result.push(nV2);
  66872. result.push(nV3);
  66873. }
  66874. if (!v3Out) {
  66875. nV1 = vertices[index + 2].clone();
  66876. nV2 = clipVertices(nV1, vertices[index]);
  66877. nV3 = clipVertices(nV1, vertices[index + 1]);
  66878. result.push(nV1);
  66879. result.push(nV2);
  66880. result.push(nV3);
  66881. }
  66882. break;
  66883. case 3:
  66884. break;
  66885. }
  66886. }
  66887. return result;
  66888. };
  66889. for (var index = 0; index < indices.length; index += 3) {
  66890. var faceVertices = new Array();
  66891. faceVertices.push(extractDecalVector3(index));
  66892. faceVertices.push(extractDecalVector3(index + 1));
  66893. faceVertices.push(extractDecalVector3(index + 2));
  66894. // Clip
  66895. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66896. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66897. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66898. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66899. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66900. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66901. if (faceVertices.length === 0) {
  66902. continue;
  66903. }
  66904. // Add UVs and get back to world
  66905. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66906. var vertex = faceVertices[vIndex];
  66907. //TODO check for Int32Array | Uint32Array | Uint16Array
  66908. vertexData.indices.push(currentVertexDataIndex);
  66909. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66910. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66911. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66912. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66913. currentVertexDataIndex++;
  66914. }
  66915. }
  66916. // Return mesh
  66917. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66918. vertexData.applyToMesh(decal);
  66919. decal.position = position.clone();
  66920. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66921. return decal;
  66922. };
  66923. // Privates
  66924. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66925. // extrusion geometry
  66926. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66927. var tangents = path3D.getTangents();
  66928. var normals = path3D.getNormals();
  66929. var binormals = path3D.getBinormals();
  66930. var distances = path3D.getDistances();
  66931. var angle = 0;
  66932. var returnScale = function () { return scale !== null ? scale : 1; };
  66933. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66934. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66935. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66936. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66937. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66938. for (var i = 0; i < curve.length; i++) {
  66939. var shapePath = new Array();
  66940. var angleStep = rotate(i, distances[i]);
  66941. var scaleRatio = scl(i, distances[i]);
  66942. for (var p = 0; p < shape.length; p++) {
  66943. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66944. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66945. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66946. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66947. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66948. shapePath[p] = rotated;
  66949. }
  66950. shapePaths[index] = shapePath;
  66951. angle += angleStep;
  66952. index++;
  66953. }
  66954. // cap
  66955. var capPath = function (shapePath) {
  66956. var pointCap = Array();
  66957. var barycenter = BABYLON.Vector3.Zero();
  66958. var i;
  66959. for (i = 0; i < shapePath.length; i++) {
  66960. barycenter.addInPlace(shapePath[i]);
  66961. }
  66962. barycenter.scaleInPlace(1.0 / shapePath.length);
  66963. for (i = 0; i < shapePath.length; i++) {
  66964. pointCap.push(barycenter);
  66965. }
  66966. return pointCap;
  66967. };
  66968. switch (cap) {
  66969. case BABYLON.Mesh.NO_CAP:
  66970. break;
  66971. case BABYLON.Mesh.CAP_START:
  66972. shapePaths[0] = capPath(shapePaths[2]);
  66973. shapePaths[1] = shapePaths[2];
  66974. break;
  66975. case BABYLON.Mesh.CAP_END:
  66976. shapePaths[index] = shapePaths[index - 1];
  66977. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66978. break;
  66979. case BABYLON.Mesh.CAP_ALL:
  66980. shapePaths[0] = capPath(shapePaths[2]);
  66981. shapePaths[1] = shapePaths[2];
  66982. shapePaths[index] = shapePaths[index - 1];
  66983. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66984. break;
  66985. default:
  66986. break;
  66987. }
  66988. return shapePaths;
  66989. };
  66990. var path3D;
  66991. var pathArray;
  66992. if (instance) { // instance update
  66993. path3D = (instance.path3D).update(curve);
  66994. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66995. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66996. return instance;
  66997. }
  66998. // extruded shape creation
  66999. path3D = new BABYLON.Path3D(curve);
  67000. var newShapePaths = new Array();
  67001. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67002. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  67003. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  67004. extrudedGeneric.pathArray = pathArray;
  67005. extrudedGeneric.path3D = path3D;
  67006. extrudedGeneric.cap = cap;
  67007. return extrudedGeneric;
  67008. };
  67009. return MeshBuilder;
  67010. }());
  67011. BABYLON.MeshBuilder = MeshBuilder;
  67012. })(BABYLON || (BABYLON = {}));
  67013. //# sourceMappingURL=babylon.meshBuilder.js.map
  67014. var BABYLON;
  67015. (function (BABYLON) {
  67016. /**
  67017. * Draco compression (https://google.github.io/draco/)
  67018. *
  67019. * This class wraps the Draco module.
  67020. *
  67021. * **Encoder**
  67022. *
  67023. * The encoder is not currently implemented.
  67024. *
  67025. * **Decoder**
  67026. *
  67027. * 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.
  67028. *
  67029. * To update the configuration, use the following code:
  67030. * ```javascript
  67031. * BABYLON.DracoCompression.Configuration = {
  67032. * decoder: {
  67033. * wasmUrl: "<url to the WebAssembly library>",
  67034. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  67035. * fallbackUrl: "<url to the fallback JavaScript library>",
  67036. * }
  67037. * };
  67038. * ```
  67039. *
  67040. * 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.
  67041. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  67042. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  67043. *
  67044. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  67045. * ```javascript
  67046. * var dracoCompression = new BABYLON.DracoCompression();
  67047. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  67048. * [BABYLON.VertexBuffer.PositionKind]: 0
  67049. * });
  67050. * ```
  67051. *
  67052. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  67053. */
  67054. var DracoCompression = /** @class */ (function () {
  67055. /**
  67056. * Constructor
  67057. */
  67058. function DracoCompression() {
  67059. }
  67060. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  67061. /**
  67062. * Returns true if the decoder is available.
  67063. */
  67064. get: function () {
  67065. if (typeof DracoDecoderModule !== "undefined") {
  67066. return true;
  67067. }
  67068. var decoder = DracoCompression.Configuration.decoder;
  67069. if (decoder) {
  67070. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67071. return true;
  67072. }
  67073. if (decoder.fallbackUrl) {
  67074. return true;
  67075. }
  67076. }
  67077. return false;
  67078. },
  67079. enumerable: true,
  67080. configurable: true
  67081. });
  67082. /**
  67083. * Stop all async operations and release resources.
  67084. */
  67085. DracoCompression.prototype.dispose = function () {
  67086. };
  67087. /**
  67088. * Decode Draco compressed mesh data to vertex data.
  67089. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  67090. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  67091. * @returns A promise that resolves with the decoded vertex data
  67092. */
  67093. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  67094. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  67095. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  67096. var module = wrappedModule.module;
  67097. var vertexData = new BABYLON.VertexData();
  67098. var buffer = new module.DecoderBuffer();
  67099. buffer.Init(dataView, dataView.byteLength);
  67100. var decoder = new module.Decoder();
  67101. var geometry;
  67102. var status;
  67103. try {
  67104. var type = decoder.GetEncodedGeometryType(buffer);
  67105. switch (type) {
  67106. case module.TRIANGULAR_MESH:
  67107. geometry = new module.Mesh();
  67108. status = decoder.DecodeBufferToMesh(buffer, geometry);
  67109. break;
  67110. case module.POINT_CLOUD:
  67111. geometry = new module.PointCloud();
  67112. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  67113. break;
  67114. default:
  67115. throw new Error("Invalid geometry type " + type);
  67116. }
  67117. if (!status.ok() || !geometry.ptr) {
  67118. throw new Error(status.error_msg());
  67119. }
  67120. var numPoints = geometry.num_points();
  67121. if (type === module.TRIANGULAR_MESH) {
  67122. var numFaces = geometry.num_faces();
  67123. var faceIndices = new module.DracoInt32Array();
  67124. try {
  67125. var indices = new Uint32Array(numFaces * 3);
  67126. for (var i = 0; i < numFaces; i++) {
  67127. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  67128. var offset = i * 3;
  67129. indices[offset + 0] = faceIndices.GetValue(0);
  67130. indices[offset + 1] = faceIndices.GetValue(1);
  67131. indices[offset + 2] = faceIndices.GetValue(2);
  67132. }
  67133. vertexData.indices = indices;
  67134. }
  67135. finally {
  67136. module.destroy(faceIndices);
  67137. }
  67138. }
  67139. for (var kind in attributes) {
  67140. var uniqueId = attributes[kind];
  67141. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  67142. var dracoData = new module.DracoFloat32Array();
  67143. try {
  67144. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  67145. var babylonData = new Float32Array(numPoints * attribute.num_components());
  67146. for (var i = 0; i < babylonData.length; i++) {
  67147. babylonData[i] = dracoData.GetValue(i);
  67148. }
  67149. vertexData.set(babylonData, kind);
  67150. }
  67151. finally {
  67152. module.destroy(dracoData);
  67153. }
  67154. }
  67155. }
  67156. finally {
  67157. if (geometry) {
  67158. module.destroy(geometry);
  67159. }
  67160. module.destroy(decoder);
  67161. module.destroy(buffer);
  67162. }
  67163. return vertexData;
  67164. });
  67165. };
  67166. DracoCompression._GetDecoderModule = function () {
  67167. if (!DracoCompression._DecoderModulePromise) {
  67168. var promise = null;
  67169. var config_1 = {};
  67170. if (typeof DracoDecoderModule !== "undefined") {
  67171. promise = Promise.resolve();
  67172. }
  67173. else {
  67174. var decoder = DracoCompression.Configuration.decoder;
  67175. if (decoder) {
  67176. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  67177. promise = Promise.all([
  67178. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  67179. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  67180. config_1.wasmBinary = data;
  67181. })
  67182. ]);
  67183. }
  67184. else if (decoder.fallbackUrl) {
  67185. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  67186. }
  67187. }
  67188. }
  67189. if (!promise) {
  67190. throw new Error("Draco decoder module is not available");
  67191. }
  67192. DracoCompression._DecoderModulePromise = promise.then(function () {
  67193. return new Promise(function (resolve) {
  67194. config_1.onModuleLoaded = function (decoderModule) {
  67195. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  67196. resolve({ module: decoderModule });
  67197. };
  67198. DracoDecoderModule(config_1);
  67199. });
  67200. });
  67201. }
  67202. return DracoCompression._DecoderModulePromise;
  67203. };
  67204. DracoCompression._LoadScriptAsync = function (url) {
  67205. return new Promise(function (resolve, reject) {
  67206. BABYLON.Tools.LoadScript(url, function () {
  67207. resolve();
  67208. }, function (message) {
  67209. reject(new Error(message));
  67210. });
  67211. });
  67212. };
  67213. DracoCompression._LoadFileAsync = function (url) {
  67214. return new Promise(function (resolve, reject) {
  67215. BABYLON.Tools.LoadFile(url, function (data) {
  67216. resolve(data);
  67217. }, undefined, undefined, true, function (request, exception) {
  67218. reject(exception);
  67219. });
  67220. });
  67221. };
  67222. /**
  67223. * The configuration. Defaults to the following urls:
  67224. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  67225. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  67226. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67227. */
  67228. DracoCompression.Configuration = {
  67229. decoder: {
  67230. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  67231. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  67232. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  67233. }
  67234. };
  67235. return DracoCompression;
  67236. }());
  67237. BABYLON.DracoCompression = DracoCompression;
  67238. })(BABYLON || (BABYLON = {}));
  67239. //# sourceMappingURL=babylon.dracoCompression.js.map
  67240. var BABYLON;
  67241. (function (BABYLON) {
  67242. // Sets the default audio engine to Babylon JS.
  67243. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  67244. /**
  67245. * This represents the default audio engine used in babylon.
  67246. * It is responsible to play, synchronize and analyse sounds throughout the application.
  67247. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67248. */
  67249. var AudioEngine = /** @class */ (function () {
  67250. /**
  67251. * Instantiates a new audio engine.
  67252. *
  67253. * There should be only one per page as some browsers restrict the number
  67254. * of audio contexts you can create.
  67255. * @param engine defines the hosting engine
  67256. */
  67257. function AudioEngine(engine) {
  67258. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  67259. var _this = this;
  67260. this._audioContext = null;
  67261. this._audioContextInitialized = false;
  67262. this._muteButton = null;
  67263. /**
  67264. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  67265. */
  67266. this.canUseWebAudio = false;
  67267. /**
  67268. * Defines if Babylon should emit a warning if WebAudio is not supported.
  67269. * @ignoreNaming
  67270. */
  67271. this.WarnedWebAudioUnsupported = false;
  67272. /**
  67273. * Gets whether or not mp3 are supported by your browser.
  67274. */
  67275. this.isMP3supported = false;
  67276. /**
  67277. * Gets whether or not ogg are supported by your browser.
  67278. */
  67279. this.isOGGsupported = false;
  67280. /**
  67281. * Gets whether audio has been unlocked on the device.
  67282. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  67283. * a user interaction has happened.
  67284. */
  67285. this.unlocked = true;
  67286. /**
  67287. * Defines if the audio engine relies on a custom unlocked button.
  67288. * In this case, the embedded button will not be displayed.
  67289. */
  67290. this.useCustomUnlockedButton = false;
  67291. /**
  67292. * Event raised when audio has been unlocked on the browser.
  67293. */
  67294. this.onAudioUnlockedObservable = new BABYLON.Observable();
  67295. /**
  67296. * Event raised when audio has been locked on the browser.
  67297. */
  67298. this.onAudioLockedObservable = new BABYLON.Observable();
  67299. this._tryToRun = false;
  67300. this._onResize = function () {
  67301. _this._moveButtonToTopLeft();
  67302. };
  67303. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  67304. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  67305. this.canUseWebAudio = true;
  67306. }
  67307. var audioElem = document.createElement('audio');
  67308. this._engine = engine;
  67309. try {
  67310. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  67311. this.isMP3supported = true;
  67312. }
  67313. }
  67314. catch (e) {
  67315. // protect error during capability check.
  67316. }
  67317. try {
  67318. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  67319. this.isOGGsupported = true;
  67320. }
  67321. }
  67322. catch (e) {
  67323. // protect error during capability check.
  67324. }
  67325. }
  67326. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  67327. /**
  67328. * Gets the current AudioContext if available.
  67329. */
  67330. get: function () {
  67331. if (!this._audioContextInitialized) {
  67332. this._initializeAudioContext();
  67333. }
  67334. else {
  67335. if (!this.unlocked && !this._muteButton) {
  67336. this._displayMuteButton();
  67337. }
  67338. }
  67339. return this._audioContext;
  67340. },
  67341. enumerable: true,
  67342. configurable: true
  67343. });
  67344. /**
  67345. * Flags the audio engine in Locked state.
  67346. * This happens due to new browser policies preventing audio to autoplay.
  67347. */
  67348. AudioEngine.prototype.lock = function () {
  67349. this._triggerSuspendedState();
  67350. };
  67351. /**
  67352. * Unlocks the audio engine once a user action has been done on the dom.
  67353. * This is helpful to resume play once browser policies have been satisfied.
  67354. */
  67355. AudioEngine.prototype.unlock = function () {
  67356. this._triggerRunningState();
  67357. };
  67358. AudioEngine.prototype._resumeAudioContext = function () {
  67359. var result;
  67360. if (this._audioContext.resume) {
  67361. result = this._audioContext.resume();
  67362. }
  67363. return result || Promise.resolve();
  67364. };
  67365. AudioEngine.prototype._initializeAudioContext = function () {
  67366. var _this = this;
  67367. try {
  67368. if (this.canUseWebAudio) {
  67369. this._audioContext = new AudioContext();
  67370. // create a global volume gain node
  67371. this.masterGain = this._audioContext.createGain();
  67372. this.masterGain.gain.value = 1;
  67373. this.masterGain.connect(this._audioContext.destination);
  67374. this._audioContextInitialized = true;
  67375. if (this._audioContext.state === "running") {
  67376. // Do not wait for the promise to unlock.
  67377. this._triggerRunningState();
  67378. }
  67379. else {
  67380. if (this._audioContext && this._audioContext.resume) {
  67381. this._resumeAudioContext().then(function () {
  67382. _this._triggerRunningState();
  67383. }).catch(function () {
  67384. // Can not resume automatically
  67385. // Needs user action
  67386. _this.lock();
  67387. });
  67388. }
  67389. }
  67390. }
  67391. }
  67392. catch (e) {
  67393. this.canUseWebAudio = false;
  67394. BABYLON.Tools.Error("Web Audio: " + e.message);
  67395. }
  67396. };
  67397. AudioEngine.prototype._triggerRunningState = function () {
  67398. var _this = this;
  67399. if (this._tryToRun) {
  67400. return;
  67401. }
  67402. this._tryToRun = true;
  67403. this._resumeAudioContext()
  67404. .then(function () {
  67405. _this._tryToRun = false;
  67406. _this.unlocked = true;
  67407. if (_this._muteButton) {
  67408. _this._hideMuteButton();
  67409. }
  67410. // Notify users that the audio stack is unlocked/unmuted
  67411. _this.onAudioUnlockedObservable.notifyObservers(_this);
  67412. }).catch(function () {
  67413. _this._tryToRun = false;
  67414. _this.unlocked = false;
  67415. });
  67416. };
  67417. AudioEngine.prototype._triggerSuspendedState = function () {
  67418. this.unlocked = false;
  67419. this.onAudioLockedObservable.notifyObservers(this);
  67420. this._displayMuteButton();
  67421. };
  67422. AudioEngine.prototype._displayMuteButton = function () {
  67423. var _this = this;
  67424. if (this.useCustomUnlockedButton) {
  67425. return;
  67426. }
  67427. this._canvas = this._engine.getRenderingCanvas();
  67428. this._muteButton = document.createElement("BUTTON");
  67429. this._muteButton.className = "babylonUnmuteIcon";
  67430. this._muteButton.id = "babylonUnmuteIconBtn";
  67431. this._muteButton.title = "Unmute";
  67432. 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) }";
  67433. var style = document.createElement('style');
  67434. style.appendChild(document.createTextNode(css));
  67435. document.getElementsByTagName('head')[0].appendChild(style);
  67436. document.body.appendChild(this._muteButton);
  67437. this._moveButtonToTopLeft();
  67438. this._muteButton.addEventListener('mousedown', function () {
  67439. _this._triggerRunningState();
  67440. }, true);
  67441. this._muteButton.addEventListener('touchend', function () {
  67442. _this._triggerRunningState();
  67443. }, true);
  67444. this._muteButton.addEventListener('click', function () {
  67445. _this._triggerRunningState();
  67446. }, true);
  67447. window.addEventListener("resize", this._onResize);
  67448. };
  67449. AudioEngine.prototype._moveButtonToTopLeft = function () {
  67450. if (this._canvas && this._muteButton) {
  67451. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  67452. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  67453. }
  67454. };
  67455. AudioEngine.prototype._hideMuteButton = function () {
  67456. if (this._muteButton) {
  67457. document.body.removeChild(this._muteButton);
  67458. this._muteButton = null;
  67459. }
  67460. };
  67461. /**
  67462. * Destroy and release the resources associated with the audio ccontext.
  67463. */
  67464. AudioEngine.prototype.dispose = function () {
  67465. if (this.canUseWebAudio && this._audioContextInitialized) {
  67466. if (this._connectedAnalyser && this._audioContext) {
  67467. this._connectedAnalyser.stopDebugCanvas();
  67468. this._connectedAnalyser.dispose();
  67469. this.masterGain.disconnect();
  67470. this.masterGain.connect(this._audioContext.destination);
  67471. this._connectedAnalyser = null;
  67472. }
  67473. this.masterGain.gain.value = 1;
  67474. }
  67475. this.WarnedWebAudioUnsupported = false;
  67476. this._hideMuteButton();
  67477. window.removeEventListener("resize", this._onResize);
  67478. this.onAudioUnlockedObservable.clear();
  67479. this.onAudioLockedObservable.clear();
  67480. };
  67481. /**
  67482. * Gets the global volume sets on the master gain.
  67483. * @returns the global volume if set or -1 otherwise
  67484. */
  67485. AudioEngine.prototype.getGlobalVolume = function () {
  67486. if (this.canUseWebAudio && this._audioContextInitialized) {
  67487. return this.masterGain.gain.value;
  67488. }
  67489. else {
  67490. return -1;
  67491. }
  67492. };
  67493. /**
  67494. * Sets the global volume of your experience (sets on the master gain).
  67495. * @param newVolume Defines the new global volume of the application
  67496. */
  67497. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  67498. if (this.canUseWebAudio && this._audioContextInitialized) {
  67499. this.masterGain.gain.value = newVolume;
  67500. }
  67501. };
  67502. /**
  67503. * Connect the audio engine to an audio analyser allowing some amazing
  67504. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  67505. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  67506. * @param analyser The analyser to connect to the engine
  67507. */
  67508. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  67509. if (this._connectedAnalyser) {
  67510. this._connectedAnalyser.stopDebugCanvas();
  67511. }
  67512. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  67513. this._connectedAnalyser = analyser;
  67514. this.masterGain.disconnect();
  67515. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  67516. }
  67517. };
  67518. return AudioEngine;
  67519. }());
  67520. BABYLON.AudioEngine = AudioEngine;
  67521. })(BABYLON || (BABYLON = {}));
  67522. //# sourceMappingURL=babylon.audioEngine.js.map
  67523. var BABYLON;
  67524. (function (BABYLON) {
  67525. /**
  67526. * Defines a sound that can be played in the application.
  67527. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  67528. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67529. */
  67530. var Sound = /** @class */ (function () {
  67531. /**
  67532. * Create a sound and attach it to a scene
  67533. * @param name Name of your sound
  67534. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  67535. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  67536. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  67537. */
  67538. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67539. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67540. var _this = this;
  67541. /**
  67542. * Does the sound autoplay once loaded.
  67543. */
  67544. this.autoplay = false;
  67545. /**
  67546. * Does the sound loop after it finishes playing once.
  67547. */
  67548. this.loop = false;
  67549. /**
  67550. * Does the sound use a custom attenuation curve to simulate the falloff
  67551. * happening when the source gets further away from the camera.
  67552. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67553. */
  67554. this.useCustomAttenuation = false;
  67555. /**
  67556. * Is this sound currently played.
  67557. */
  67558. this.isPlaying = false;
  67559. /**
  67560. * Is this sound currently paused.
  67561. */
  67562. this.isPaused = false;
  67563. /**
  67564. * Does this sound enables spatial sound.
  67565. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67566. */
  67567. this.spatialSound = false;
  67568. /**
  67569. * Define the reference distance the sound should be heard perfectly.
  67570. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67571. */
  67572. this.refDistance = 1;
  67573. /**
  67574. * Define the roll off factor of spatial sounds.
  67575. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67576. */
  67577. this.rolloffFactor = 1;
  67578. /**
  67579. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  67580. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67581. */
  67582. this.maxDistance = 100;
  67583. /**
  67584. * Define the distance attenuation model the sound will follow.
  67585. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67586. */
  67587. this.distanceModel = "linear";
  67588. /**
  67589. * Observable event when the current playing sound finishes.
  67590. */
  67591. this.onEndedObservable = new BABYLON.Observable();
  67592. this._panningModel = "equalpower";
  67593. this._playbackRate = 1;
  67594. this._streaming = false;
  67595. this._startTime = 0;
  67596. this._startOffset = 0;
  67597. this._position = BABYLON.Vector3.Zero();
  67598. /** @hidden */
  67599. this._positionInEmitterSpace = false;
  67600. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67601. this._volume = 1;
  67602. this._isReadyToPlay = false;
  67603. this._isDirectional = false;
  67604. // Used if you'd like to create a directional sound.
  67605. // If not set, the sound will be omnidirectional
  67606. this._coneInnerAngle = 360;
  67607. this._coneOuterAngle = 360;
  67608. this._coneOuterGain = 0;
  67609. this._isOutputConnected = false;
  67610. this._urlType = "Unknown";
  67611. this.name = name;
  67612. this._scene = scene;
  67613. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67614. if (!compo) {
  67615. compo = new BABYLON.AudioSceneComponent(scene);
  67616. scene._addComponent(compo);
  67617. }
  67618. this._readyToPlayCallback = readyToPlayCallback;
  67619. // Default custom attenuation function is a linear attenuation
  67620. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67621. if (currentDistance < maxDistance) {
  67622. return currentVolume * (1 - currentDistance / maxDistance);
  67623. }
  67624. else {
  67625. return 0;
  67626. }
  67627. };
  67628. if (options) {
  67629. this.autoplay = options.autoplay || false;
  67630. this.loop = options.loop || false;
  67631. // if volume === 0, we need another way to check this option
  67632. if (options.volume !== undefined) {
  67633. this._volume = options.volume;
  67634. }
  67635. this.spatialSound = options.spatialSound || false;
  67636. this.maxDistance = options.maxDistance || 100;
  67637. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67638. this.rolloffFactor = options.rolloffFactor || 1;
  67639. this.refDistance = options.refDistance || 1;
  67640. this.distanceModel = options.distanceModel || "linear";
  67641. this._playbackRate = options.playbackRate || 1;
  67642. this._streaming = options.streaming || false;
  67643. }
  67644. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67645. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67646. this._soundGain.gain.value = this._volume;
  67647. this._inputAudioNode = this._soundGain;
  67648. this._outputAudioNode = this._soundGain;
  67649. if (this.spatialSound) {
  67650. this._createSpatialParameters();
  67651. }
  67652. this._scene.mainSoundTrack.AddSound(this);
  67653. var validParameter = true;
  67654. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67655. if (urlOrArrayBuffer) {
  67656. try {
  67657. if (typeof (urlOrArrayBuffer) === "string") {
  67658. this._urlType = "String";
  67659. }
  67660. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67661. this._urlType = "ArrayBuffer";
  67662. }
  67663. else if (urlOrArrayBuffer instanceof MediaStream) {
  67664. this._urlType = "MediaStream";
  67665. }
  67666. else if (Array.isArray(urlOrArrayBuffer)) {
  67667. this._urlType = "Array";
  67668. }
  67669. var urls = [];
  67670. var codecSupportedFound = false;
  67671. switch (this._urlType) {
  67672. case "MediaStream":
  67673. this._streaming = true;
  67674. this._isReadyToPlay = true;
  67675. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67676. if (this.autoplay) {
  67677. this.play();
  67678. }
  67679. if (this._readyToPlayCallback) {
  67680. this._readyToPlayCallback();
  67681. }
  67682. break;
  67683. case "ArrayBuffer":
  67684. if (urlOrArrayBuffer.byteLength > 0) {
  67685. codecSupportedFound = true;
  67686. this._soundLoaded(urlOrArrayBuffer);
  67687. }
  67688. break;
  67689. case "String":
  67690. urls.push(urlOrArrayBuffer);
  67691. case "Array":
  67692. if (urls.length === 0)
  67693. urls = urlOrArrayBuffer;
  67694. // If we found a supported format, we load it immediately and stop the loop
  67695. for (var i = 0; i < urls.length; i++) {
  67696. var url = urls[i];
  67697. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67698. codecSupportedFound = true;
  67699. }
  67700. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67701. codecSupportedFound = true;
  67702. }
  67703. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67704. codecSupportedFound = true;
  67705. }
  67706. if (url.indexOf("blob:") !== -1) {
  67707. codecSupportedFound = true;
  67708. }
  67709. if (codecSupportedFound) {
  67710. // Loading sound using XHR2
  67711. if (!this._streaming) {
  67712. this._scene._loadFile(url, function (data) {
  67713. _this._soundLoaded(data);
  67714. }, undefined, true, true, function (exception) {
  67715. if (exception) {
  67716. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67717. }
  67718. BABYLON.Tools.Error("Sound creation aborted.");
  67719. _this._scene.mainSoundTrack.RemoveSound(_this);
  67720. });
  67721. }
  67722. // Streaming sound using HTML5 Audio tag
  67723. else {
  67724. this._htmlAudioElement = new Audio(url);
  67725. this._htmlAudioElement.controls = false;
  67726. this._htmlAudioElement.loop = this.loop;
  67727. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67728. this._htmlAudioElement.preload = "auto";
  67729. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67730. _this._isReadyToPlay = true;
  67731. if (_this.autoplay) {
  67732. _this.play();
  67733. }
  67734. if (_this._readyToPlayCallback) {
  67735. _this._readyToPlayCallback();
  67736. }
  67737. });
  67738. document.body.appendChild(this._htmlAudioElement);
  67739. this._htmlAudioElement.load();
  67740. }
  67741. break;
  67742. }
  67743. }
  67744. break;
  67745. default:
  67746. validParameter = false;
  67747. break;
  67748. }
  67749. if (!validParameter) {
  67750. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67751. }
  67752. else {
  67753. if (!codecSupportedFound) {
  67754. this._isReadyToPlay = true;
  67755. // Simulating a ready to play event to avoid breaking code path
  67756. if (this._readyToPlayCallback) {
  67757. window.setTimeout(function () {
  67758. if (_this._readyToPlayCallback) {
  67759. _this._readyToPlayCallback();
  67760. }
  67761. }, 1000);
  67762. }
  67763. }
  67764. }
  67765. }
  67766. catch (ex) {
  67767. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67768. this._scene.mainSoundTrack.RemoveSound(this);
  67769. }
  67770. }
  67771. }
  67772. else {
  67773. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67774. this._scene.mainSoundTrack.AddSound(this);
  67775. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67776. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67777. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67778. }
  67779. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67780. if (this._readyToPlayCallback) {
  67781. window.setTimeout(function () {
  67782. if (_this._readyToPlayCallback) {
  67783. _this._readyToPlayCallback();
  67784. }
  67785. }, 1000);
  67786. }
  67787. }
  67788. }
  67789. /**
  67790. * Release the sound and its associated resources
  67791. */
  67792. Sound.prototype.dispose = function () {
  67793. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67794. if (this.isPlaying) {
  67795. this.stop();
  67796. }
  67797. this._isReadyToPlay = false;
  67798. if (this.soundTrackId === -1) {
  67799. this._scene.mainSoundTrack.RemoveSound(this);
  67800. }
  67801. else if (this._scene.soundTracks) {
  67802. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67803. }
  67804. if (this._soundGain) {
  67805. this._soundGain.disconnect();
  67806. this._soundGain = null;
  67807. }
  67808. if (this._soundPanner) {
  67809. this._soundPanner.disconnect();
  67810. this._soundPanner = null;
  67811. }
  67812. if (this._soundSource) {
  67813. this._soundSource.disconnect();
  67814. this._soundSource = null;
  67815. }
  67816. this._audioBuffer = null;
  67817. if (this._htmlAudioElement) {
  67818. this._htmlAudioElement.pause();
  67819. this._htmlAudioElement.src = "";
  67820. document.body.removeChild(this._htmlAudioElement);
  67821. }
  67822. if (this._streamingSource) {
  67823. this._streamingSource.disconnect();
  67824. }
  67825. if (this._connectedMesh && this._registerFunc) {
  67826. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67827. this._connectedMesh = null;
  67828. }
  67829. }
  67830. };
  67831. /**
  67832. * Gets if the sounds is ready to be played or not.
  67833. * @returns true if ready, otherwise false
  67834. */
  67835. Sound.prototype.isReady = function () {
  67836. return this._isReadyToPlay;
  67837. };
  67838. Sound.prototype._soundLoaded = function (audioData) {
  67839. var _this = this;
  67840. if (!BABYLON.Engine.audioEngine.audioContext) {
  67841. return;
  67842. }
  67843. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67844. _this._audioBuffer = buffer;
  67845. _this._isReadyToPlay = true;
  67846. if (_this.autoplay) {
  67847. _this.play();
  67848. }
  67849. if (_this._readyToPlayCallback) {
  67850. _this._readyToPlayCallback();
  67851. }
  67852. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67853. };
  67854. /**
  67855. * Sets the data of the sound from an audiobuffer
  67856. * @param audioBuffer The audioBuffer containing the data
  67857. */
  67858. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67859. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67860. this._audioBuffer = audioBuffer;
  67861. this._isReadyToPlay = true;
  67862. }
  67863. };
  67864. /**
  67865. * Updates the current sounds options such as maxdistance, loop...
  67866. * @param options A JSON object containing values named as the object properties
  67867. */
  67868. Sound.prototype.updateOptions = function (options) {
  67869. if (options) {
  67870. this.loop = options.loop || this.loop;
  67871. this.maxDistance = options.maxDistance || this.maxDistance;
  67872. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67873. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67874. this.refDistance = options.refDistance || this.refDistance;
  67875. this.distanceModel = options.distanceModel || this.distanceModel;
  67876. this._playbackRate = options.playbackRate || this._playbackRate;
  67877. this._updateSpatialParameters();
  67878. if (this.isPlaying) {
  67879. if (this._streaming && this._htmlAudioElement) {
  67880. this._htmlAudioElement.playbackRate = this._playbackRate;
  67881. }
  67882. else {
  67883. if (this._soundSource) {
  67884. this._soundSource.playbackRate.value = this._playbackRate;
  67885. }
  67886. }
  67887. }
  67888. }
  67889. };
  67890. Sound.prototype._createSpatialParameters = function () {
  67891. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67892. if (this._scene.headphone) {
  67893. this._panningModel = "HRTF";
  67894. }
  67895. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67896. this._updateSpatialParameters();
  67897. this._soundPanner.connect(this._outputAudioNode);
  67898. this._inputAudioNode = this._soundPanner;
  67899. }
  67900. };
  67901. Sound.prototype._updateSpatialParameters = function () {
  67902. if (this.spatialSound && this._soundPanner) {
  67903. if (this.useCustomAttenuation) {
  67904. // Tricks to disable in a way embedded Web Audio attenuation
  67905. this._soundPanner.distanceModel = "linear";
  67906. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67907. this._soundPanner.refDistance = 1;
  67908. this._soundPanner.rolloffFactor = 1;
  67909. this._soundPanner.panningModel = this._panningModel;
  67910. }
  67911. else {
  67912. this._soundPanner.distanceModel = this.distanceModel;
  67913. this._soundPanner.maxDistance = this.maxDistance;
  67914. this._soundPanner.refDistance = this.refDistance;
  67915. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67916. this._soundPanner.panningModel = this._panningModel;
  67917. }
  67918. }
  67919. };
  67920. /**
  67921. * Switch the panning model to HRTF:
  67922. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  67923. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67924. */
  67925. Sound.prototype.switchPanningModelToHRTF = function () {
  67926. this._panningModel = "HRTF";
  67927. this._switchPanningModel();
  67928. };
  67929. /**
  67930. * Switch the panning model to Equal Power:
  67931. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  67932. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  67933. */
  67934. Sound.prototype.switchPanningModelToEqualPower = function () {
  67935. this._panningModel = "equalpower";
  67936. this._switchPanningModel();
  67937. };
  67938. Sound.prototype._switchPanningModel = function () {
  67939. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67940. this._soundPanner.panningModel = this._panningModel;
  67941. }
  67942. };
  67943. /**
  67944. * Connect this sound to a sound track audio node like gain...
  67945. * @param soundTrackAudioNode the sound track audio node to connect to
  67946. */
  67947. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67948. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67949. if (this._isOutputConnected) {
  67950. this._outputAudioNode.disconnect();
  67951. }
  67952. this._outputAudioNode.connect(soundTrackAudioNode);
  67953. this._isOutputConnected = true;
  67954. }
  67955. };
  67956. /**
  67957. * Transform this sound into a directional source
  67958. * @param coneInnerAngle Size of the inner cone in degree
  67959. * @param coneOuterAngle Size of the outer cone in degree
  67960. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67961. */
  67962. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67963. if (coneOuterAngle < coneInnerAngle) {
  67964. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67965. return;
  67966. }
  67967. this._coneInnerAngle = coneInnerAngle;
  67968. this._coneOuterAngle = coneOuterAngle;
  67969. this._coneOuterGain = coneOuterGain;
  67970. this._isDirectional = true;
  67971. if (this.isPlaying && this.loop) {
  67972. this.stop();
  67973. this.play();
  67974. }
  67975. };
  67976. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67977. /**
  67978. * Gets or sets the inner angle for the directional cone.
  67979. */
  67980. get: function () {
  67981. return this._coneInnerAngle;
  67982. },
  67983. /**
  67984. * Gets or sets the inner angle for the directional cone.
  67985. */
  67986. set: function (value) {
  67987. if (value != this._coneInnerAngle) {
  67988. if (this._coneOuterAngle < value) {
  67989. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67990. return;
  67991. }
  67992. this._coneInnerAngle = value;
  67993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67994. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67995. }
  67996. }
  67997. },
  67998. enumerable: true,
  67999. configurable: true
  68000. });
  68001. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  68002. /**
  68003. * Gets or sets the outer angle for the directional cone.
  68004. */
  68005. get: function () {
  68006. return this._coneOuterAngle;
  68007. },
  68008. /**
  68009. * Gets or sets the outer angle for the directional cone.
  68010. */
  68011. set: function (value) {
  68012. if (value != this._coneOuterAngle) {
  68013. if (value < this._coneInnerAngle) {
  68014. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68015. return;
  68016. }
  68017. this._coneOuterAngle = value;
  68018. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  68019. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68020. }
  68021. }
  68022. },
  68023. enumerable: true,
  68024. configurable: true
  68025. });
  68026. /**
  68027. * Sets the position of the emitter if spatial sound is enabled
  68028. * @param newPosition Defines the new posisiton
  68029. */
  68030. Sound.prototype.setPosition = function (newPosition) {
  68031. this._position = newPosition;
  68032. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68033. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68034. }
  68035. };
  68036. /**
  68037. * Sets the local direction of the emitter if spatial sound is enabled
  68038. * @param newLocalDirection Defines the new local direction
  68039. */
  68040. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  68041. this._localDirection = newLocalDirection;
  68042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  68043. this._updateDirection();
  68044. }
  68045. };
  68046. Sound.prototype._updateDirection = function () {
  68047. if (!this._connectedMesh || !this._soundPanner) {
  68048. return;
  68049. }
  68050. var mat = this._connectedMesh.getWorldMatrix();
  68051. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  68052. direction.normalize();
  68053. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  68054. };
  68055. /** @hidden */
  68056. Sound.prototype.updateDistanceFromListener = function () {
  68057. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  68058. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  68059. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  68060. }
  68061. };
  68062. /**
  68063. * Sets a new custom attenuation function for the sound.
  68064. * @param callback Defines the function used for the attenuation
  68065. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68066. */
  68067. Sound.prototype.setAttenuationFunction = function (callback) {
  68068. this._customAttenuationFunction = callback;
  68069. };
  68070. /**
  68071. * Play the sound
  68072. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  68073. * @param offset (optional) Start the sound setting it at a specific time
  68074. */
  68075. Sound.prototype.play = function (time, offset) {
  68076. var _this = this;
  68077. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  68078. try {
  68079. if (this._startOffset < 0) {
  68080. time = -this._startOffset;
  68081. this._startOffset = 0;
  68082. }
  68083. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68084. if (!this._soundSource || !this._streamingSource) {
  68085. if (this.spatialSound && this._soundPanner) {
  68086. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  68087. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  68088. }
  68089. if (this._isDirectional) {
  68090. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  68091. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  68092. this._soundPanner.coneOuterGain = this._coneOuterGain;
  68093. if (this._connectedMesh) {
  68094. this._updateDirection();
  68095. }
  68096. else {
  68097. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  68098. }
  68099. }
  68100. }
  68101. }
  68102. if (this._streaming) {
  68103. if (!this._streamingSource) {
  68104. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  68105. this._htmlAudioElement.onended = function () { _this._onended(); };
  68106. this._htmlAudioElement.playbackRate = this._playbackRate;
  68107. }
  68108. this._streamingSource.disconnect();
  68109. this._streamingSource.connect(this._inputAudioNode);
  68110. if (this._htmlAudioElement) {
  68111. // required to manage properly the new suspended default state of Chrome
  68112. // When the option 'streaming: true' is used, we need first to wait for
  68113. // the audio engine to be unlocked by a user gesture before trying to play
  68114. // an HTML Audio elememt
  68115. var tryToPlay = function () {
  68116. if (BABYLON.Engine.audioEngine.unlocked) {
  68117. var playPromise = _this._htmlAudioElement.play();
  68118. // In browsers that don’t yet support this functionality,
  68119. // playPromise won’t be defined.
  68120. if (playPromise !== undefined) {
  68121. playPromise.catch(function (error) {
  68122. // Automatic playback failed.
  68123. // Waiting for the audio engine to be unlocked by user click on unmute
  68124. BABYLON.Engine.audioEngine.lock();
  68125. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68126. });
  68127. }
  68128. }
  68129. else {
  68130. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  68131. }
  68132. };
  68133. tryToPlay();
  68134. }
  68135. }
  68136. else {
  68137. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  68138. this._soundSource.buffer = this._audioBuffer;
  68139. this._soundSource.connect(this._inputAudioNode);
  68140. this._soundSource.loop = this.loop;
  68141. this._soundSource.playbackRate.value = this._playbackRate;
  68142. this._soundSource.onended = function () { _this._onended(); };
  68143. if (this._soundSource.buffer) {
  68144. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  68145. }
  68146. }
  68147. this._startTime = startTime;
  68148. this.isPlaying = true;
  68149. this.isPaused = false;
  68150. }
  68151. catch (ex) {
  68152. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  68153. }
  68154. }
  68155. };
  68156. Sound.prototype._onended = function () {
  68157. this.isPlaying = false;
  68158. if (this.onended) {
  68159. this.onended();
  68160. }
  68161. this.onEndedObservable.notifyObservers(this);
  68162. };
  68163. /**
  68164. * Stop the sound
  68165. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  68166. */
  68167. Sound.prototype.stop = function (time) {
  68168. if (this.isPlaying) {
  68169. if (this._streaming) {
  68170. if (this._htmlAudioElement) {
  68171. this._htmlAudioElement.pause();
  68172. // Test needed for Firefox or it will generate an Invalid State Error
  68173. if (this._htmlAudioElement.currentTime > 0) {
  68174. this._htmlAudioElement.currentTime = 0;
  68175. }
  68176. }
  68177. else {
  68178. this._streamingSource.disconnect();
  68179. }
  68180. }
  68181. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  68182. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  68183. this._soundSource.stop(stopTime);
  68184. this._soundSource.onended = function () { };
  68185. if (!this.isPaused) {
  68186. this._startOffset = 0;
  68187. }
  68188. }
  68189. this.isPlaying = false;
  68190. }
  68191. };
  68192. /**
  68193. * Put the sound in pause
  68194. */
  68195. Sound.prototype.pause = function () {
  68196. if (this.isPlaying) {
  68197. this.isPaused = true;
  68198. if (this._streaming) {
  68199. if (this._htmlAudioElement) {
  68200. this._htmlAudioElement.pause();
  68201. }
  68202. else {
  68203. this._streamingSource.disconnect();
  68204. }
  68205. }
  68206. else if (BABYLON.Engine.audioEngine.audioContext) {
  68207. this.stop(0);
  68208. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  68209. }
  68210. }
  68211. };
  68212. /**
  68213. * Sets a dedicated volume for this sounds
  68214. * @param newVolume Define the new volume of the sound
  68215. * @param time Define in how long the sound should be at this value
  68216. */
  68217. Sound.prototype.setVolume = function (newVolume, time) {
  68218. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  68219. if (time && BABYLON.Engine.audioEngine.audioContext) {
  68220. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  68221. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  68222. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  68223. }
  68224. else {
  68225. this._soundGain.gain.value = newVolume;
  68226. }
  68227. }
  68228. this._volume = newVolume;
  68229. };
  68230. /**
  68231. * Set the sound play back rate
  68232. * @param newPlaybackRate Define the playback rate the sound should be played at
  68233. */
  68234. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  68235. this._playbackRate = newPlaybackRate;
  68236. if (this.isPlaying) {
  68237. if (this._streaming && this._htmlAudioElement) {
  68238. this._htmlAudioElement.playbackRate = this._playbackRate;
  68239. }
  68240. else if (this._soundSource) {
  68241. this._soundSource.playbackRate.value = this._playbackRate;
  68242. }
  68243. }
  68244. };
  68245. /**
  68246. * Gets the volume of the sound.
  68247. * @returns the volume of the sound
  68248. */
  68249. Sound.prototype.getVolume = function () {
  68250. return this._volume;
  68251. };
  68252. /**
  68253. * Attach the sound to a dedicated mesh
  68254. * @param meshToConnectTo The mesh to connect the sound with
  68255. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68256. */
  68257. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  68258. var _this = this;
  68259. if (this._connectedMesh && this._registerFunc) {
  68260. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68261. this._registerFunc = null;
  68262. }
  68263. this._connectedMesh = meshToConnectTo;
  68264. if (!this.spatialSound) {
  68265. this.spatialSound = true;
  68266. this._createSpatialParameters();
  68267. if (this.isPlaying && this.loop) {
  68268. this.stop();
  68269. this.play();
  68270. }
  68271. }
  68272. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  68273. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  68274. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  68275. };
  68276. /**
  68277. * Detach the sound from the previously attached mesh
  68278. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  68279. */
  68280. Sound.prototype.detachFromMesh = function () {
  68281. if (this._connectedMesh && this._registerFunc) {
  68282. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68283. this._registerFunc = null;
  68284. this._connectedMesh = null;
  68285. }
  68286. };
  68287. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  68288. if (!node.getBoundingInfo) {
  68289. return;
  68290. }
  68291. var mesh = node;
  68292. if (this._positionInEmitterSpace) {
  68293. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  68294. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  68295. }
  68296. else {
  68297. var boundingInfo = mesh.getBoundingInfo();
  68298. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  68299. }
  68300. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  68301. this._updateDirection();
  68302. }
  68303. };
  68304. /**
  68305. * Clone the current sound in the scene.
  68306. * @returns the new sound clone
  68307. */
  68308. Sound.prototype.clone = function () {
  68309. var _this = this;
  68310. if (!this._streaming) {
  68311. var setBufferAndRun = function () {
  68312. if (_this._isReadyToPlay) {
  68313. clonedSound._audioBuffer = _this.getAudioBuffer();
  68314. clonedSound._isReadyToPlay = true;
  68315. if (clonedSound.autoplay) {
  68316. clonedSound.play();
  68317. }
  68318. }
  68319. else {
  68320. window.setTimeout(setBufferAndRun, 300);
  68321. }
  68322. };
  68323. var currentOptions = {
  68324. autoplay: this.autoplay, loop: this.loop,
  68325. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  68326. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  68327. refDistance: this.refDistance, distanceModel: this.distanceModel
  68328. };
  68329. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  68330. if (this.useCustomAttenuation) {
  68331. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  68332. }
  68333. clonedSound.setPosition(this._position);
  68334. clonedSound.setPlaybackRate(this._playbackRate);
  68335. setBufferAndRun();
  68336. return clonedSound;
  68337. }
  68338. // Can't clone a streaming sound
  68339. else {
  68340. return null;
  68341. }
  68342. };
  68343. /**
  68344. * Gets the current underlying audio buffer containing the data
  68345. * @returns the audio buffer
  68346. */
  68347. Sound.prototype.getAudioBuffer = function () {
  68348. return this._audioBuffer;
  68349. };
  68350. /**
  68351. * Serializes the Sound in a JSON representation
  68352. * @returns the JSON representation of the sound
  68353. */
  68354. Sound.prototype.serialize = function () {
  68355. var serializationObject = {
  68356. name: this.name,
  68357. url: this.name,
  68358. autoplay: this.autoplay,
  68359. loop: this.loop,
  68360. volume: this._volume,
  68361. spatialSound: this.spatialSound,
  68362. maxDistance: this.maxDistance,
  68363. rolloffFactor: this.rolloffFactor,
  68364. refDistance: this.refDistance,
  68365. distanceModel: this.distanceModel,
  68366. playbackRate: this._playbackRate,
  68367. panningModel: this._panningModel,
  68368. soundTrackId: this.soundTrackId
  68369. };
  68370. if (this.spatialSound) {
  68371. if (this._connectedMesh)
  68372. serializationObject.connectedMeshId = this._connectedMesh.id;
  68373. serializationObject.position = this._position.asArray();
  68374. serializationObject.refDistance = this.refDistance;
  68375. serializationObject.distanceModel = this.distanceModel;
  68376. serializationObject.isDirectional = this._isDirectional;
  68377. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  68378. serializationObject.coneInnerAngle = this._coneInnerAngle;
  68379. serializationObject.coneOuterAngle = this._coneOuterAngle;
  68380. serializationObject.coneOuterGain = this._coneOuterGain;
  68381. }
  68382. return serializationObject;
  68383. };
  68384. /**
  68385. * Parse a JSON representation of a sound to innstantiate in a given scene
  68386. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  68387. * @param scene Define the scene the new parsed sound should be created in
  68388. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  68389. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  68390. * @returns the newly parsed sound
  68391. */
  68392. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  68393. var soundName = parsedSound.name;
  68394. var soundUrl;
  68395. if (parsedSound.url) {
  68396. soundUrl = rootUrl + parsedSound.url;
  68397. }
  68398. else {
  68399. soundUrl = rootUrl + soundName;
  68400. }
  68401. var options = {
  68402. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  68403. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  68404. rolloffFactor: parsedSound.rolloffFactor,
  68405. refDistance: parsedSound.refDistance,
  68406. distanceModel: parsedSound.distanceModel,
  68407. playbackRate: parsedSound.playbackRate
  68408. };
  68409. var newSound;
  68410. if (!sourceSound) {
  68411. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  68412. scene._addPendingData(newSound);
  68413. }
  68414. else {
  68415. var setBufferAndRun = function () {
  68416. if (sourceSound._isReadyToPlay) {
  68417. newSound._audioBuffer = sourceSound.getAudioBuffer();
  68418. newSound._isReadyToPlay = true;
  68419. if (newSound.autoplay) {
  68420. newSound.play();
  68421. }
  68422. }
  68423. else {
  68424. window.setTimeout(setBufferAndRun, 300);
  68425. }
  68426. };
  68427. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  68428. setBufferAndRun();
  68429. }
  68430. if (parsedSound.position) {
  68431. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  68432. newSound.setPosition(soundPosition);
  68433. }
  68434. if (parsedSound.isDirectional) {
  68435. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  68436. if (parsedSound.localDirectionToMesh) {
  68437. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  68438. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  68439. }
  68440. }
  68441. if (parsedSound.connectedMeshId) {
  68442. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  68443. if (connectedMesh) {
  68444. newSound.attachToMesh(connectedMesh);
  68445. }
  68446. }
  68447. return newSound;
  68448. };
  68449. return Sound;
  68450. }());
  68451. BABYLON.Sound = Sound;
  68452. })(BABYLON || (BABYLON = {}));
  68453. //# sourceMappingURL=babylon.sound.js.map
  68454. var BABYLON;
  68455. (function (BABYLON) {
  68456. /**
  68457. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  68458. * It will be also used in a future release to apply effects on a specific track.
  68459. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68460. */
  68461. var SoundTrack = /** @class */ (function () {
  68462. /**
  68463. * Creates a new sound track.
  68464. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  68465. * @param scene Define the scene the sound track belongs to
  68466. * @param options
  68467. */
  68468. function SoundTrack(scene, options) {
  68469. if (options === void 0) { options = {}; }
  68470. /**
  68471. * The unique identifier of the sound track in the scene.
  68472. */
  68473. this.id = -1;
  68474. this._isMainTrack = false;
  68475. this._isInitialized = false;
  68476. this._scene = scene;
  68477. this.soundCollection = new Array();
  68478. this._options = options;
  68479. if (!this._isMainTrack && this._scene.soundTracks) {
  68480. this._scene.soundTracks.push(this);
  68481. this.id = this._scene.soundTracks.length - 1;
  68482. }
  68483. }
  68484. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  68485. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68486. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  68487. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  68488. if (this._options) {
  68489. if (this._options.volume) {
  68490. this._outputAudioNode.gain.value = this._options.volume;
  68491. }
  68492. if (this._options.mainTrack) {
  68493. this._isMainTrack = this._options.mainTrack;
  68494. }
  68495. }
  68496. this._isInitialized = true;
  68497. }
  68498. };
  68499. /**
  68500. * Release the sound track and its associated resources
  68501. */
  68502. SoundTrack.prototype.dispose = function () {
  68503. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  68504. if (this._connectedAnalyser) {
  68505. this._connectedAnalyser.stopDebugCanvas();
  68506. }
  68507. while (this.soundCollection.length) {
  68508. this.soundCollection[0].dispose();
  68509. }
  68510. if (this._outputAudioNode) {
  68511. this._outputAudioNode.disconnect();
  68512. }
  68513. this._outputAudioNode = null;
  68514. }
  68515. };
  68516. /**
  68517. * Adds a sound to this sound track
  68518. * @param sound define the cound to add
  68519. * @ignoreNaming
  68520. */
  68521. SoundTrack.prototype.AddSound = function (sound) {
  68522. if (!this._isInitialized) {
  68523. this._initializeSoundTrackAudioGraph();
  68524. }
  68525. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68526. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  68527. }
  68528. if (sound.soundTrackId) {
  68529. if (sound.soundTrackId === -1) {
  68530. this._scene.mainSoundTrack.RemoveSound(sound);
  68531. }
  68532. else if (this._scene.soundTracks) {
  68533. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  68534. }
  68535. }
  68536. this.soundCollection.push(sound);
  68537. sound.soundTrackId = this.id;
  68538. };
  68539. /**
  68540. * Removes a sound to this sound track
  68541. * @param sound define the cound to remove
  68542. * @ignoreNaming
  68543. */
  68544. SoundTrack.prototype.RemoveSound = function (sound) {
  68545. var index = this.soundCollection.indexOf(sound);
  68546. if (index !== -1) {
  68547. this.soundCollection.splice(index, 1);
  68548. }
  68549. };
  68550. /**
  68551. * Set a global volume for the full sound track.
  68552. * @param newVolume Define the new volume of the sound track
  68553. */
  68554. SoundTrack.prototype.setVolume = function (newVolume) {
  68555. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68556. this._outputAudioNode.gain.value = newVolume;
  68557. }
  68558. };
  68559. /**
  68560. * Switch the panning model to HRTF:
  68561. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  68562. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68563. */
  68564. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  68565. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68566. for (var i = 0; i < this.soundCollection.length; i++) {
  68567. this.soundCollection[i].switchPanningModelToHRTF();
  68568. }
  68569. }
  68570. };
  68571. /**
  68572. * Switch the panning model to Equal Power:
  68573. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  68574. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68575. */
  68576. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  68577. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68578. for (var i = 0; i < this.soundCollection.length; i++) {
  68579. this.soundCollection[i].switchPanningModelToEqualPower();
  68580. }
  68581. }
  68582. };
  68583. /**
  68584. * Connect the sound track to an audio analyser allowing some amazing
  68585. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68586. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68587. * @param analyser The analyser to connect to the engine
  68588. */
  68589. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  68590. if (this._connectedAnalyser) {
  68591. this._connectedAnalyser.stopDebugCanvas();
  68592. }
  68593. this._connectedAnalyser = analyser;
  68594. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  68595. this._outputAudioNode.disconnect();
  68596. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  68597. }
  68598. };
  68599. return SoundTrack;
  68600. }());
  68601. BABYLON.SoundTrack = SoundTrack;
  68602. })(BABYLON || (BABYLON = {}));
  68603. //# sourceMappingURL=babylon.soundtrack.js.map
  68604. var BABYLON;
  68605. (function (BABYLON) {
  68606. /**
  68607. * Class used to work with sound analyzer using fast fourier transform (FFT)
  68608. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68609. */
  68610. var Analyser = /** @class */ (function () {
  68611. /**
  68612. * Creates a new analyser
  68613. * @param scene defines hosting scene
  68614. */
  68615. function Analyser(scene) {
  68616. /**
  68617. * Gets or sets the smoothing
  68618. * @ignorenaming
  68619. */
  68620. this.SMOOTHING = 0.75;
  68621. /**
  68622. * Gets or sets the FFT table size
  68623. * @ignorenaming
  68624. */
  68625. this.FFT_SIZE = 512;
  68626. /**
  68627. * Gets or sets the bar graph amplitude
  68628. * @ignorenaming
  68629. */
  68630. this.BARGRAPHAMPLITUDE = 256;
  68631. /**
  68632. * Gets or sets the position of the debug canvas
  68633. * @ignorenaming
  68634. */
  68635. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  68636. /**
  68637. * Gets or sets the debug canvas size
  68638. * @ignorenaming
  68639. */
  68640. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  68641. this._scene = scene;
  68642. this._audioEngine = BABYLON.Engine.audioEngine;
  68643. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  68644. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  68645. this._webAudioAnalyser.minDecibels = -140;
  68646. this._webAudioAnalyser.maxDecibels = 0;
  68647. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68648. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  68649. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  68650. }
  68651. }
  68652. /**
  68653. * Get the number of data values you will have to play with for the visualization
  68654. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  68655. * @returns a number
  68656. */
  68657. Analyser.prototype.getFrequencyBinCount = function () {
  68658. if (this._audioEngine.canUseWebAudio) {
  68659. return this._webAudioAnalyser.frequencyBinCount;
  68660. }
  68661. else {
  68662. return 0;
  68663. }
  68664. };
  68665. /**
  68666. * Gets the current frequency data as a byte array
  68667. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68668. * @returns a Uint8Array
  68669. */
  68670. Analyser.prototype.getByteFrequencyData = function () {
  68671. if (this._audioEngine.canUseWebAudio) {
  68672. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68673. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68674. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  68675. }
  68676. return this._byteFreqs;
  68677. };
  68678. /**
  68679. * Gets the current waveform as a byte array
  68680. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  68681. * @returns a Uint8Array
  68682. */
  68683. Analyser.prototype.getByteTimeDomainData = function () {
  68684. if (this._audioEngine.canUseWebAudio) {
  68685. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68686. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68687. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  68688. }
  68689. return this._byteTime;
  68690. };
  68691. /**
  68692. * Gets the current frequency data as a float array
  68693. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  68694. * @returns a Float32Array
  68695. */
  68696. Analyser.prototype.getFloatFrequencyData = function () {
  68697. if (this._audioEngine.canUseWebAudio) {
  68698. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68699. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68700. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68701. }
  68702. return this._floatFreqs;
  68703. };
  68704. /**
  68705. * Renders the debug canvas
  68706. */
  68707. Analyser.prototype.drawDebugCanvas = function () {
  68708. var _this = this;
  68709. if (this._audioEngine.canUseWebAudio) {
  68710. if (!this._debugCanvas) {
  68711. this._debugCanvas = document.createElement("canvas");
  68712. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68713. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68714. this._debugCanvas.style.position = "absolute";
  68715. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68716. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68717. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68718. document.body.appendChild(this._debugCanvas);
  68719. this._registerFunc = function () {
  68720. _this.drawDebugCanvas();
  68721. };
  68722. this._scene.registerBeforeRender(this._registerFunc);
  68723. }
  68724. if (this._registerFunc && this._debugCanvasContext) {
  68725. var workingArray = this.getByteFrequencyData();
  68726. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68727. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68728. // Draw the frequency domain chart.
  68729. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68730. var value = workingArray[i];
  68731. var percent = value / this.BARGRAPHAMPLITUDE;
  68732. var height = this.DEBUGCANVASSIZE.height * percent;
  68733. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68734. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68735. var hue = i / this.getFrequencyBinCount() * 360;
  68736. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68737. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68738. }
  68739. }
  68740. }
  68741. };
  68742. /**
  68743. * Stops rendering the debug canvas and removes it
  68744. */
  68745. Analyser.prototype.stopDebugCanvas = function () {
  68746. if (this._debugCanvas) {
  68747. if (this._registerFunc) {
  68748. this._scene.unregisterBeforeRender(this._registerFunc);
  68749. this._registerFunc = null;
  68750. }
  68751. document.body.removeChild(this._debugCanvas);
  68752. this._debugCanvas = null;
  68753. this._debugCanvasContext = null;
  68754. }
  68755. };
  68756. /**
  68757. * Connects two audio nodes
  68758. * @param inputAudioNode defines first node to connect
  68759. * @param outputAudioNode defines second node to connect
  68760. */
  68761. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68762. if (this._audioEngine.canUseWebAudio) {
  68763. inputAudioNode.connect(this._webAudioAnalyser);
  68764. this._webAudioAnalyser.connect(outputAudioNode);
  68765. }
  68766. };
  68767. /**
  68768. * Releases all associated resources
  68769. */
  68770. Analyser.prototype.dispose = function () {
  68771. if (this._audioEngine.canUseWebAudio) {
  68772. this._webAudioAnalyser.disconnect();
  68773. }
  68774. };
  68775. return Analyser;
  68776. }());
  68777. BABYLON.Analyser = Analyser;
  68778. })(BABYLON || (BABYLON = {}));
  68779. //# sourceMappingURL=babylon.analyser.js.map
  68780. var BABYLON;
  68781. (function (BABYLON) {
  68782. /**
  68783. * Wraps one or more Sound objects and selects one with random weight for playback.
  68784. */
  68785. var WeightedSound = /** @class */ (function () {
  68786. /**
  68787. * Creates a new WeightedSound from the list of sounds given.
  68788. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68789. * @param sounds Array of Sounds that will be selected from.
  68790. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68791. */
  68792. function WeightedSound(loop, sounds, weights) {
  68793. var _this = this;
  68794. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68795. this.loop = false;
  68796. this._coneInnerAngle = 360;
  68797. this._coneOuterAngle = 360;
  68798. this._volume = 1;
  68799. /** A Sound is currently playing. */
  68800. this.isPlaying = false;
  68801. /** A Sound is currently paused. */
  68802. this.isPaused = false;
  68803. this._sounds = [];
  68804. this._weights = [];
  68805. if (sounds.length !== weights.length) {
  68806. throw new Error('Sounds length does not equal weights length');
  68807. }
  68808. this.loop = loop;
  68809. this._weights = weights;
  68810. // Normalize the weights
  68811. var weightSum = 0;
  68812. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68813. var weight = weights_1[_i];
  68814. weightSum += weight;
  68815. }
  68816. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68817. for (var i = 0; i < this._weights.length; i++) {
  68818. this._weights[i] *= invWeightSum;
  68819. }
  68820. this._sounds = sounds;
  68821. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68822. var sound = _b[_a];
  68823. sound.onEndedObservable.add(function () { _this._onended(); });
  68824. }
  68825. }
  68826. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68827. /**
  68828. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68829. */
  68830. get: function () {
  68831. return this._coneInnerAngle;
  68832. },
  68833. /**
  68834. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68835. */
  68836. set: function (value) {
  68837. if (value !== this._coneInnerAngle) {
  68838. if (this._coneOuterAngle < value) {
  68839. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68840. return;
  68841. }
  68842. this._coneInnerAngle = value;
  68843. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68844. var sound = _a[_i];
  68845. sound.directionalConeInnerAngle = value;
  68846. }
  68847. }
  68848. },
  68849. enumerable: true,
  68850. configurable: true
  68851. });
  68852. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68853. /**
  68854. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68855. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68856. */
  68857. get: function () {
  68858. return this._coneOuterAngle;
  68859. },
  68860. /**
  68861. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68862. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68863. */
  68864. set: function (value) {
  68865. if (value !== this._coneOuterAngle) {
  68866. if (value < this._coneInnerAngle) {
  68867. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68868. return;
  68869. }
  68870. this._coneOuterAngle = value;
  68871. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68872. var sound = _a[_i];
  68873. sound.directionalConeOuterAngle = value;
  68874. }
  68875. }
  68876. },
  68877. enumerable: true,
  68878. configurable: true
  68879. });
  68880. Object.defineProperty(WeightedSound.prototype, "volume", {
  68881. /**
  68882. * Playback volume.
  68883. */
  68884. get: function () {
  68885. return this._volume;
  68886. },
  68887. /**
  68888. * Playback volume.
  68889. */
  68890. set: function (value) {
  68891. if (value !== this._volume) {
  68892. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68893. var sound = _a[_i];
  68894. sound.setVolume(value);
  68895. }
  68896. }
  68897. },
  68898. enumerable: true,
  68899. configurable: true
  68900. });
  68901. WeightedSound.prototype._onended = function () {
  68902. if (this._currentIndex !== undefined) {
  68903. this._sounds[this._currentIndex].autoplay = false;
  68904. }
  68905. if (this.loop && this.isPlaying) {
  68906. this.play();
  68907. }
  68908. else {
  68909. this.isPlaying = false;
  68910. }
  68911. };
  68912. /**
  68913. * Suspend playback
  68914. */
  68915. WeightedSound.prototype.pause = function () {
  68916. this.isPaused = true;
  68917. if (this._currentIndex !== undefined) {
  68918. this._sounds[this._currentIndex].pause();
  68919. }
  68920. };
  68921. /**
  68922. * Stop playback
  68923. */
  68924. WeightedSound.prototype.stop = function () {
  68925. this.isPlaying = false;
  68926. if (this._currentIndex !== undefined) {
  68927. this._sounds[this._currentIndex].stop();
  68928. }
  68929. };
  68930. /**
  68931. * Start playback.
  68932. * @param startOffset Position the clip head at a specific time in seconds.
  68933. */
  68934. WeightedSound.prototype.play = function (startOffset) {
  68935. if (!this.isPaused) {
  68936. this.stop();
  68937. var randomValue = Math.random();
  68938. var total = 0;
  68939. for (var i = 0; i < this._weights.length; i++) {
  68940. total += this._weights[i];
  68941. if (randomValue <= total) {
  68942. this._currentIndex = i;
  68943. break;
  68944. }
  68945. }
  68946. }
  68947. var sound = this._sounds[this._currentIndex];
  68948. if (sound.isReady()) {
  68949. sound.play(0, this.isPaused ? undefined : startOffset);
  68950. }
  68951. else {
  68952. sound.autoplay = true;
  68953. }
  68954. this.isPlaying = true;
  68955. this.isPaused = false;
  68956. };
  68957. return WeightedSound;
  68958. }());
  68959. BABYLON.WeightedSound = WeightedSound;
  68960. })(BABYLON || (BABYLON = {}));
  68961. //# sourceMappingURL=babylon.weightedsound.js.map
  68962. var BABYLON;
  68963. (function (BABYLON) {
  68964. // Adds the parser to the scene parsers.
  68965. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68966. // TODO: add sound
  68967. var loadedSounds = [];
  68968. var loadedSound;
  68969. container.sounds = container.sounds || [];
  68970. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68971. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68972. var parsedSound = parsedData.sounds[index];
  68973. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68974. if (!parsedSound.url)
  68975. parsedSound.url = parsedSound.name;
  68976. if (!loadedSounds[parsedSound.url]) {
  68977. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68978. loadedSounds[parsedSound.url] = loadedSound;
  68979. container.sounds.push(loadedSound);
  68980. }
  68981. else {
  68982. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68983. }
  68984. }
  68985. else {
  68986. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68987. }
  68988. }
  68989. }
  68990. loadedSounds = [];
  68991. });
  68992. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68993. get: function () {
  68994. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68995. if (!compo) {
  68996. compo = new AudioSceneComponent(this);
  68997. this._addComponent(compo);
  68998. }
  68999. if (!this._mainSoundTrack) {
  69000. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  69001. }
  69002. return this._mainSoundTrack;
  69003. },
  69004. enumerable: true,
  69005. configurable: true
  69006. });
  69007. BABYLON.Scene.prototype.getSoundByName = function (name) {
  69008. var index;
  69009. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  69010. if (this.mainSoundTrack.soundCollection[index].name === name) {
  69011. return this.mainSoundTrack.soundCollection[index];
  69012. }
  69013. }
  69014. if (this.soundTracks) {
  69015. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  69016. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  69017. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  69018. return this.soundTracks[sdIndex].soundCollection[index];
  69019. }
  69020. }
  69021. }
  69022. }
  69023. return null;
  69024. };
  69025. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  69026. get: function () {
  69027. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69028. if (!compo) {
  69029. compo = new AudioSceneComponent(this);
  69030. this._addComponent(compo);
  69031. }
  69032. return compo.audioEnabled;
  69033. },
  69034. set: function (value) {
  69035. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69036. if (!compo) {
  69037. compo = new AudioSceneComponent(this);
  69038. this._addComponent(compo);
  69039. }
  69040. if (value) {
  69041. compo.enableAudio();
  69042. }
  69043. else {
  69044. compo.disableAudio();
  69045. }
  69046. },
  69047. enumerable: true,
  69048. configurable: true
  69049. });
  69050. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  69051. get: function () {
  69052. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69053. if (!compo) {
  69054. compo = new AudioSceneComponent(this);
  69055. this._addComponent(compo);
  69056. }
  69057. return compo.headphone;
  69058. },
  69059. set: function (value) {
  69060. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69061. if (!compo) {
  69062. compo = new AudioSceneComponent(this);
  69063. this._addComponent(compo);
  69064. }
  69065. if (value) {
  69066. compo.switchAudioModeForHeadphones();
  69067. }
  69068. else {
  69069. compo.switchAudioModeForNormalSpeakers();
  69070. }
  69071. },
  69072. enumerable: true,
  69073. configurable: true
  69074. });
  69075. /**
  69076. * Defines the sound scene component responsible to manage any sounds
  69077. * in a given scene.
  69078. */
  69079. var AudioSceneComponent = /** @class */ (function () {
  69080. /**
  69081. * Creates a new instance of the component for the given scene
  69082. * @param scene Defines the scene to register the component in
  69083. */
  69084. function AudioSceneComponent(scene) {
  69085. /**
  69086. * The component name helpfull to identify the component in the list of scene components.
  69087. */
  69088. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  69089. this._audioEnabled = true;
  69090. this._headphone = false;
  69091. this.scene = scene;
  69092. scene.soundTracks = new Array();
  69093. scene.sounds = new Array();
  69094. }
  69095. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  69096. /**
  69097. * Gets whether audio is enabled or not.
  69098. * Please use related enable/disable method to switch state.
  69099. */
  69100. get: function () {
  69101. return this._audioEnabled;
  69102. },
  69103. enumerable: true,
  69104. configurable: true
  69105. });
  69106. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  69107. /**
  69108. * Gets whether audio is outputing to headphone or not.
  69109. * Please use the according Switch methods to change output.
  69110. */
  69111. get: function () {
  69112. return this._headphone;
  69113. },
  69114. enumerable: true,
  69115. configurable: true
  69116. });
  69117. /**
  69118. * Registers the component in a given scene
  69119. */
  69120. AudioSceneComponent.prototype.register = function () {
  69121. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  69122. };
  69123. /**
  69124. * Rebuilds the elements related to this component in case of
  69125. * context lost for instance.
  69126. */
  69127. AudioSceneComponent.prototype.rebuild = function () {
  69128. // Nothing to do here. (Not rendering related)
  69129. };
  69130. /**
  69131. * Serializes the component data to the specified json object
  69132. * @param serializationObject The object to serialize to
  69133. */
  69134. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  69135. serializationObject.sounds = [];
  69136. if (this.scene.soundTracks) {
  69137. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  69138. var soundtrack = this.scene.soundTracks[index];
  69139. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69140. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69141. }
  69142. }
  69143. }
  69144. };
  69145. /**
  69146. * Adds all the element from the container to the scene
  69147. * @param container the container holding the elements
  69148. */
  69149. AudioSceneComponent.prototype.addFromContainer = function (container) {
  69150. var _this = this;
  69151. if (!container.sounds) {
  69152. return;
  69153. }
  69154. container.sounds.forEach(function (sound) {
  69155. sound.play();
  69156. sound.autoplay = true;
  69157. _this.scene.mainSoundTrack.AddSound(sound);
  69158. });
  69159. };
  69160. /**
  69161. * Removes all the elements in the container from the scene
  69162. * @param container contains the elements to remove
  69163. */
  69164. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  69165. var _this = this;
  69166. if (!container.sounds) {
  69167. return;
  69168. }
  69169. container.sounds.forEach(function (sound) {
  69170. sound.stop();
  69171. sound.autoplay = false;
  69172. _this.scene.mainSoundTrack.RemoveSound(sound);
  69173. });
  69174. };
  69175. /**
  69176. * Disposes the component and the associated ressources.
  69177. */
  69178. AudioSceneComponent.prototype.dispose = function () {
  69179. var scene = this.scene;
  69180. if (scene._mainSoundTrack) {
  69181. scene.mainSoundTrack.dispose();
  69182. }
  69183. if (scene.soundTracks) {
  69184. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  69185. scene.soundTracks[scIndex].dispose();
  69186. }
  69187. }
  69188. };
  69189. /**
  69190. * Disables audio in the associated scene.
  69191. */
  69192. AudioSceneComponent.prototype.disableAudio = function () {
  69193. var scene = this.scene;
  69194. this._audioEnabled = false;
  69195. var i;
  69196. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69197. scene.mainSoundTrack.soundCollection[i].pause();
  69198. }
  69199. if (scene.soundTracks) {
  69200. for (i = 0; i < scene.soundTracks.length; i++) {
  69201. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69202. scene.soundTracks[i].soundCollection[j].pause();
  69203. }
  69204. }
  69205. }
  69206. };
  69207. /**
  69208. * Enables audio in the associated scene.
  69209. */
  69210. AudioSceneComponent.prototype.enableAudio = function () {
  69211. var scene = this.scene;
  69212. this._audioEnabled = true;
  69213. var i;
  69214. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69215. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  69216. scene.mainSoundTrack.soundCollection[i].play();
  69217. }
  69218. }
  69219. if (scene.soundTracks) {
  69220. for (i = 0; i < scene.soundTracks.length; i++) {
  69221. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69222. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  69223. scene.soundTracks[i].soundCollection[j].play();
  69224. }
  69225. }
  69226. }
  69227. }
  69228. };
  69229. /**
  69230. * Switch audio to headphone output.
  69231. */
  69232. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  69233. var scene = this.scene;
  69234. this._headphone = true;
  69235. scene.mainSoundTrack.switchPanningModelToHRTF();
  69236. if (scene.soundTracks) {
  69237. for (var i = 0; i < scene.soundTracks.length; i++) {
  69238. scene.soundTracks[i].switchPanningModelToHRTF();
  69239. }
  69240. }
  69241. };
  69242. /**
  69243. * Switch audio to normal speakers.
  69244. */
  69245. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  69246. var scene = this.scene;
  69247. this._headphone = false;
  69248. scene.mainSoundTrack.switchPanningModelToEqualPower();
  69249. if (scene.soundTracks) {
  69250. for (var i = 0; i < scene.soundTracks.length; i++) {
  69251. scene.soundTracks[i].switchPanningModelToEqualPower();
  69252. }
  69253. }
  69254. };
  69255. AudioSceneComponent.prototype._afterRender = function () {
  69256. var scene = this.scene;
  69257. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  69258. return;
  69259. }
  69260. var listeningCamera;
  69261. var audioEngine = BABYLON.Engine.audioEngine;
  69262. if (scene.activeCameras.length > 0) {
  69263. listeningCamera = scene.activeCameras[0];
  69264. }
  69265. else {
  69266. listeningCamera = scene.activeCamera;
  69267. }
  69268. if (listeningCamera && audioEngine.audioContext) {
  69269. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  69270. // for VR cameras
  69271. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  69272. listeningCamera = listeningCamera.rigCameras[0];
  69273. }
  69274. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  69275. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  69276. cameraDirection.normalize();
  69277. // To avoid some errors on GearVR
  69278. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  69279. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  69280. }
  69281. var i;
  69282. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  69283. var sound = scene.mainSoundTrack.soundCollection[i];
  69284. if (sound.useCustomAttenuation) {
  69285. sound.updateDistanceFromListener();
  69286. }
  69287. }
  69288. if (scene.soundTracks) {
  69289. for (i = 0; i < scene.soundTracks.length; i++) {
  69290. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  69291. sound = scene.soundTracks[i].soundCollection[j];
  69292. if (sound.useCustomAttenuation) {
  69293. sound.updateDistanceFromListener();
  69294. }
  69295. }
  69296. }
  69297. }
  69298. }
  69299. };
  69300. return AudioSceneComponent;
  69301. }());
  69302. BABYLON.AudioSceneComponent = AudioSceneComponent;
  69303. })(BABYLON || (BABYLON = {}));
  69304. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  69305. var BABYLON;
  69306. (function (BABYLON) {
  69307. /**
  69308. * This defines an action helpful to play a defined sound on a triggered action.
  69309. */
  69310. var PlaySoundAction = /** @class */ (function (_super) {
  69311. __extends(PlaySoundAction, _super);
  69312. /**
  69313. * Instantiate the action
  69314. * @param triggerOptions defines the trigger options
  69315. * @param sound defines the sound to play
  69316. * @param condition defines the trigger related conditions
  69317. */
  69318. function PlaySoundAction(triggerOptions, sound, condition) {
  69319. var _this = _super.call(this, triggerOptions, condition) || this;
  69320. _this._sound = sound;
  69321. return _this;
  69322. }
  69323. /** @hidden */
  69324. PlaySoundAction.prototype._prepare = function () {
  69325. };
  69326. /**
  69327. * Execute the action and play the sound.
  69328. */
  69329. PlaySoundAction.prototype.execute = function () {
  69330. if (this._sound !== undefined)
  69331. this._sound.play();
  69332. };
  69333. /**
  69334. * Serializes the actions and its related information.
  69335. * @param parent defines the object to serialize in
  69336. * @returns the serialized object
  69337. */
  69338. PlaySoundAction.prototype.serialize = function (parent) {
  69339. return _super.prototype._serialize.call(this, {
  69340. name: "PlaySoundAction",
  69341. properties: [{ name: "sound", value: this._sound.name }]
  69342. }, parent);
  69343. };
  69344. return PlaySoundAction;
  69345. }(BABYLON.Action));
  69346. BABYLON.PlaySoundAction = PlaySoundAction;
  69347. /**
  69348. * This defines an action helpful to stop a defined sound on a triggered action.
  69349. */
  69350. var StopSoundAction = /** @class */ (function (_super) {
  69351. __extends(StopSoundAction, _super);
  69352. /**
  69353. * Instantiate the action
  69354. * @param triggerOptions defines the trigger options
  69355. * @param sound defines the sound to stop
  69356. * @param condition defines the trigger related conditions
  69357. */
  69358. function StopSoundAction(triggerOptions, sound, condition) {
  69359. var _this = _super.call(this, triggerOptions, condition) || this;
  69360. _this._sound = sound;
  69361. return _this;
  69362. }
  69363. /** @hidden */
  69364. StopSoundAction.prototype._prepare = function () {
  69365. };
  69366. /**
  69367. * Execute the action and stop the sound.
  69368. */
  69369. StopSoundAction.prototype.execute = function () {
  69370. if (this._sound !== undefined)
  69371. this._sound.stop();
  69372. };
  69373. /**
  69374. * Serializes the actions and its related information.
  69375. * @param parent defines the object to serialize in
  69376. * @returns the serialized object
  69377. */
  69378. StopSoundAction.prototype.serialize = function (parent) {
  69379. return _super.prototype._serialize.call(this, {
  69380. name: "StopSoundAction",
  69381. properties: [{ name: "sound", value: this._sound.name }]
  69382. }, parent);
  69383. };
  69384. return StopSoundAction;
  69385. }(BABYLON.Action));
  69386. BABYLON.StopSoundAction = StopSoundAction;
  69387. })(BABYLON || (BABYLON = {}));
  69388. //# sourceMappingURL=babylon.directAudioActions.js.map
  69389. var BABYLON;
  69390. (function (BABYLON) {
  69391. var CubeTexture = /** @class */ (function (_super) {
  69392. __extends(CubeTexture, _super);
  69393. /**
  69394. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  69395. * as prefiltered data.
  69396. * @param rootUrl defines the url of the texture or the root name of the six images
  69397. * @param scene defines the scene the texture is attached to
  69398. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  69399. * @param noMipmap defines if mipmaps should be created or not
  69400. * @param files defines the six files to load for the different faces
  69401. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  69402. * @param onError defines a callback triggered in case of error during load
  69403. * @param format defines the internal format to use for the texture once loaded
  69404. * @param prefiltered defines whether or not the texture is created from prefiltered data
  69405. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  69406. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69407. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69408. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69409. * @return the cube texture
  69410. */
  69411. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  69412. if (extensions === void 0) { extensions = null; }
  69413. if (noMipmap === void 0) { noMipmap = false; }
  69414. if (files === void 0) { files = null; }
  69415. if (onLoad === void 0) { onLoad = null; }
  69416. if (onError === void 0) { onError = null; }
  69417. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69418. if (prefiltered === void 0) { prefiltered = false; }
  69419. if (forcedExtension === void 0) { forcedExtension = null; }
  69420. if (createPolynomials === void 0) { createPolynomials = false; }
  69421. if (lodScale === void 0) { lodScale = 0.8; }
  69422. if (lodOffset === void 0) { lodOffset = 0; }
  69423. var _this = _super.call(this, scene) || this;
  69424. /**
  69425. * Gets or sets the center of the bounding box associated with the cube texture
  69426. * It must define where the camera used to render the texture was set
  69427. */
  69428. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69429. _this._rotationY = 0;
  69430. /** @hidden */
  69431. _this._prefiltered = false;
  69432. _this.name = rootUrl;
  69433. _this.url = rootUrl;
  69434. _this._noMipmap = noMipmap;
  69435. _this.hasAlpha = false;
  69436. _this._format = format;
  69437. _this.isCube = true;
  69438. _this._textureMatrix = BABYLON.Matrix.Identity();
  69439. _this._createPolynomials = createPolynomials;
  69440. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  69441. if (!rootUrl && !files) {
  69442. return _this;
  69443. }
  69444. var lastDot = rootUrl.lastIndexOf(".");
  69445. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  69446. var isDDS = (extension === ".dds");
  69447. var isEnv = (extension === ".env");
  69448. if (isEnv) {
  69449. _this.gammaSpace = false;
  69450. _this._prefiltered = false;
  69451. }
  69452. else {
  69453. _this._prefiltered = prefiltered;
  69454. if (prefiltered) {
  69455. _this.gammaSpace = false;
  69456. }
  69457. }
  69458. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  69459. if (!files) {
  69460. if (!isEnv && !isDDS && !extensions) {
  69461. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  69462. }
  69463. files = [];
  69464. if (extensions) {
  69465. for (var index = 0; index < extensions.length; index++) {
  69466. files.push(rootUrl + extensions[index]);
  69467. }
  69468. }
  69469. }
  69470. _this._files = files;
  69471. if (!_this._texture) {
  69472. if (!scene.useDelayedTextureLoading) {
  69473. if (prefiltered) {
  69474. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  69475. }
  69476. else {
  69477. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  69478. }
  69479. }
  69480. else {
  69481. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  69482. }
  69483. }
  69484. else if (onLoad) {
  69485. if (_this._texture.isReady) {
  69486. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  69487. }
  69488. else {
  69489. _this._texture.onLoadedObservable.add(onLoad);
  69490. }
  69491. }
  69492. return _this;
  69493. }
  69494. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  69495. get: function () {
  69496. return this._boundingBoxSize;
  69497. },
  69498. /**
  69499. * Gets or sets the size of the bounding box associated with the cube texture
  69500. * When defined, the cubemap will switch to local mode
  69501. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69502. * @example https://www.babylonjs-playground.com/#RNASML
  69503. */
  69504. set: function (value) {
  69505. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69506. return;
  69507. }
  69508. this._boundingBoxSize = value;
  69509. var scene = this.getScene();
  69510. if (scene) {
  69511. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69512. }
  69513. },
  69514. enumerable: true,
  69515. configurable: true
  69516. });
  69517. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  69518. /**
  69519. * Gets texture matrix rotation angle around Y axis radians.
  69520. */
  69521. get: function () {
  69522. return this._rotationY;
  69523. },
  69524. /**
  69525. * Sets texture matrix rotation angle around Y axis in radians.
  69526. */
  69527. set: function (value) {
  69528. this._rotationY = value;
  69529. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  69530. },
  69531. enumerable: true,
  69532. configurable: true
  69533. });
  69534. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  69535. var rootUrlKey = "";
  69536. files.forEach(function (url) { return rootUrlKey += url; });
  69537. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  69538. };
  69539. /**
  69540. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  69541. * @param url defines the url of the prefiltered texture
  69542. * @param scene defines the scene the texture is attached to
  69543. * @param forcedExtension defines the extension of the file if different from the url
  69544. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  69545. * @return the prefiltered texture
  69546. */
  69547. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  69548. if (forcedExtension === void 0) { forcedExtension = null; }
  69549. if (createPolynomials === void 0) { createPolynomials = true; }
  69550. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  69551. };
  69552. // Methods
  69553. CubeTexture.prototype.delayLoad = function () {
  69554. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  69555. return;
  69556. }
  69557. var scene = this.getScene();
  69558. if (!scene) {
  69559. return;
  69560. }
  69561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  69562. this._texture = this._getFromCache(this.url, this._noMipmap);
  69563. if (!this._texture) {
  69564. if (this._prefiltered) {
  69565. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  69566. }
  69567. else {
  69568. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  69569. }
  69570. }
  69571. };
  69572. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  69573. return this._textureMatrix;
  69574. };
  69575. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  69576. this._textureMatrix = value;
  69577. };
  69578. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  69579. var texture = BABYLON.SerializationHelper.Parse(function () {
  69580. var prefiltered = false;
  69581. if (parsedTexture.prefiltered) {
  69582. prefiltered = parsedTexture.prefiltered;
  69583. }
  69584. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  69585. }, parsedTexture, scene);
  69586. // Local Cubemaps
  69587. if (parsedTexture.boundingBoxPosition) {
  69588. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  69589. }
  69590. if (parsedTexture.boundingBoxSize) {
  69591. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  69592. }
  69593. // Animations
  69594. if (parsedTexture.animations) {
  69595. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  69596. var parsedAnimation = parsedTexture.animations[animationIndex];
  69597. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69598. }
  69599. }
  69600. return texture;
  69601. };
  69602. CubeTexture.prototype.clone = function () {
  69603. var _this = this;
  69604. return BABYLON.SerializationHelper.Clone(function () {
  69605. var scene = _this.getScene();
  69606. if (!scene) {
  69607. return _this;
  69608. }
  69609. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  69610. }, this);
  69611. };
  69612. __decorate([
  69613. BABYLON.serialize("rotationY")
  69614. ], CubeTexture.prototype, "rotationY", null);
  69615. return CubeTexture;
  69616. }(BABYLON.BaseTexture));
  69617. BABYLON.CubeTexture = CubeTexture;
  69618. })(BABYLON || (BABYLON = {}));
  69619. //# sourceMappingURL=babylon.cubeTexture.js.map
  69620. var BABYLON;
  69621. (function (BABYLON) {
  69622. /**
  69623. * Raw cube texture where the raw buffers are passed in
  69624. */
  69625. var RawCubeTexture = /** @class */ (function (_super) {
  69626. __extends(RawCubeTexture, _super);
  69627. /**
  69628. * Creates a cube texture where the raw buffers are passed in.
  69629. * @param scene defines the scene the texture is attached to
  69630. * @param data defines the array of data to use to create each face
  69631. * @param size defines the size of the textures
  69632. * @param format defines the format of the data
  69633. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  69634. * @param generateMipMaps defines if the engine should generate the mip levels
  69635. * @param invertY defines if data must be stored with Y axis inverted
  69636. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  69637. * @param compression defines the compression used (null by default)
  69638. */
  69639. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  69640. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69641. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69642. if (generateMipMaps === void 0) { generateMipMaps = false; }
  69643. if (invertY === void 0) { invertY = false; }
  69644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69645. if (compression === void 0) { compression = null; }
  69646. var _this = _super.call(this, "", scene) || this;
  69647. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  69648. return _this;
  69649. }
  69650. /**
  69651. * Updates the raw cube texture.
  69652. * @param data defines the data to store
  69653. * @param format defines the data format
  69654. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  69655. * @param invertY defines if data must be stored with Y axis inverted
  69656. * @param compression defines the compression used (null by default)
  69657. * @param level defines which level of the texture to update
  69658. */
  69659. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  69660. if (compression === void 0) { compression = null; }
  69661. if (level === void 0) { level = 0; }
  69662. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  69663. };
  69664. /**
  69665. * Updates a raw cube texture with RGBD encoded data.
  69666. * @param data defines the array of data [mipmap][face] to use to create each face
  69667. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  69668. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  69669. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  69670. * @returns a promsie that resolves when the operation is complete
  69671. */
  69672. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  69673. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  69674. if (lodScale === void 0) { lodScale = 0.8; }
  69675. if (lodOffset === void 0) { lodOffset = 0; }
  69676. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  69677. };
  69678. /**
  69679. * Clones the raw cube texture.
  69680. * @return a new cube texture
  69681. */
  69682. RawCubeTexture.prototype.clone = function () {
  69683. var _this = this;
  69684. return BABYLON.SerializationHelper.Clone(function () {
  69685. var scene = _this.getScene();
  69686. var internalTexture = _this._texture;
  69687. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  69688. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  69689. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  69690. }
  69691. return texture;
  69692. }, this);
  69693. };
  69694. /** @hidden */
  69695. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  69696. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  69697. internalTexture._bufferViewArrayArray = data;
  69698. internalTexture._lodGenerationScale = lodScale;
  69699. internalTexture._lodGenerationOffset = lodOffset;
  69700. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69701. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69702. internalTexture.isReady = true;
  69703. });
  69704. };
  69705. return RawCubeTexture;
  69706. }(BABYLON.CubeTexture));
  69707. BABYLON.RawCubeTexture = RawCubeTexture;
  69708. })(BABYLON || (BABYLON = {}));
  69709. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69710. var BABYLON;
  69711. (function (BABYLON) {
  69712. var RenderTargetTexture = /** @class */ (function (_super) {
  69713. __extends(RenderTargetTexture, _super);
  69714. /**
  69715. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69716. * or used a shadow, depth texture...
  69717. * @param name The friendly name of the texture
  69718. * @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)
  69719. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69720. * @param generateMipMaps True if mip maps need to be generated after render.
  69721. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69722. * @param type The type of the buffer in the RTT (int, half float, float...)
  69723. * @param isCube True if a cube texture needs to be created
  69724. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69725. * @param generateDepthBuffer True to generate a depth buffer
  69726. * @param generateStencilBuffer True to generate a stencil buffer
  69727. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69728. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69729. */
  69730. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69731. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69732. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69733. if (isCube === void 0) { isCube = false; }
  69734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69735. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69736. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69737. if (isMulti === void 0) { isMulti = false; }
  69738. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69739. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69740. _this.isCube = isCube;
  69741. _this.renderParticles = true;
  69742. _this.renderSprites = false;
  69743. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69744. _this.ignoreCameraViewport = false;
  69745. // Events
  69746. /**
  69747. * An event triggered when the texture is unbind.
  69748. */
  69749. _this.onBeforeBindObservable = new BABYLON.Observable();
  69750. /**
  69751. * An event triggered when the texture is unbind.
  69752. */
  69753. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69754. /**
  69755. * An event triggered before rendering the texture
  69756. */
  69757. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69758. /**
  69759. * An event triggered after rendering the texture
  69760. */
  69761. _this.onAfterRenderObservable = new BABYLON.Observable();
  69762. /**
  69763. * An event triggered after the texture clear
  69764. */
  69765. _this.onClearObservable = new BABYLON.Observable();
  69766. _this._currentRefreshId = -1;
  69767. _this._refreshRate = 1;
  69768. _this._samples = 1;
  69769. /**
  69770. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69771. * It must define where the camera used to render the texture is set
  69772. */
  69773. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69774. scene = _this.getScene();
  69775. if (!scene) {
  69776. return _this;
  69777. }
  69778. _this.renderList = new Array();
  69779. _this._engine = scene.getEngine();
  69780. _this.name = name;
  69781. _this.isRenderTarget = true;
  69782. _this._initialSizeParameter = size;
  69783. _this._processSizeParameter(size);
  69784. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69785. });
  69786. _this._generateMipMaps = generateMipMaps ? true : false;
  69787. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69788. // Rendering groups
  69789. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69790. _this._renderingManager._useSceneAutoClearSetup = true;
  69791. if (isMulti) {
  69792. return _this;
  69793. }
  69794. _this._renderTargetOptions = {
  69795. generateMipMaps: generateMipMaps,
  69796. type: type,
  69797. format: format,
  69798. samplingMode: samplingMode,
  69799. generateDepthBuffer: generateDepthBuffer,
  69800. generateStencilBuffer: generateStencilBuffer
  69801. };
  69802. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69803. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69804. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69805. }
  69806. if (isCube) {
  69807. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69808. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69809. _this._textureMatrix = BABYLON.Matrix.Identity();
  69810. }
  69811. else {
  69812. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69813. }
  69814. return _this;
  69815. }
  69816. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69817. get: function () {
  69818. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69819. },
  69820. enumerable: true,
  69821. configurable: true
  69822. });
  69823. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69824. get: function () {
  69825. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69826. },
  69827. enumerable: true,
  69828. configurable: true
  69829. });
  69830. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69831. get: function () {
  69832. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69833. },
  69834. enumerable: true,
  69835. configurable: true
  69836. });
  69837. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69838. /**
  69839. * Use this list to define the list of mesh you want to render.
  69840. */
  69841. get: function () {
  69842. return this._renderList;
  69843. },
  69844. set: function (value) {
  69845. this._renderList = value;
  69846. if (this._renderList) {
  69847. this._hookArray(this._renderList);
  69848. }
  69849. },
  69850. enumerable: true,
  69851. configurable: true
  69852. });
  69853. RenderTargetTexture.prototype._hookArray = function (array) {
  69854. var _this = this;
  69855. var oldPush = array.push;
  69856. array.push = function () {
  69857. var items = [];
  69858. for (var _i = 0; _i < arguments.length; _i++) {
  69859. items[_i] = arguments[_i];
  69860. }
  69861. var result = oldPush.apply(array, items);
  69862. _this.getScene().meshes.forEach(function (mesh) {
  69863. mesh._markSubMeshesAsLightDirty();
  69864. });
  69865. return result;
  69866. };
  69867. var oldSplice = array.splice;
  69868. array.splice = function (index, deleteCount) {
  69869. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69870. _this.getScene().meshes.forEach(function (mesh) {
  69871. mesh._markSubMeshesAsLightDirty();
  69872. });
  69873. return deleted;
  69874. };
  69875. };
  69876. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69877. set: function (callback) {
  69878. if (this._onAfterUnbindObserver) {
  69879. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69880. }
  69881. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69882. },
  69883. enumerable: true,
  69884. configurable: true
  69885. });
  69886. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69887. set: function (callback) {
  69888. if (this._onBeforeRenderObserver) {
  69889. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69890. }
  69891. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69892. },
  69893. enumerable: true,
  69894. configurable: true
  69895. });
  69896. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69897. set: function (callback) {
  69898. if (this._onAfterRenderObserver) {
  69899. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69900. }
  69901. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69902. },
  69903. enumerable: true,
  69904. configurable: true
  69905. });
  69906. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69907. set: function (callback) {
  69908. if (this._onClearObserver) {
  69909. this.onClearObservable.remove(this._onClearObserver);
  69910. }
  69911. this._onClearObserver = this.onClearObservable.add(callback);
  69912. },
  69913. enumerable: true,
  69914. configurable: true
  69915. });
  69916. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69917. get: function () {
  69918. return this._renderTargetOptions;
  69919. },
  69920. enumerable: true,
  69921. configurable: true
  69922. });
  69923. RenderTargetTexture.prototype._onRatioRescale = function () {
  69924. if (this._sizeRatio) {
  69925. this.resize(this._initialSizeParameter);
  69926. }
  69927. };
  69928. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69929. get: function () {
  69930. return this._boundingBoxSize;
  69931. },
  69932. /**
  69933. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69934. * When defined, the cubemap will switch to local mode
  69935. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69936. * @example https://www.babylonjs-playground.com/#RNASML
  69937. */
  69938. set: function (value) {
  69939. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69940. return;
  69941. }
  69942. this._boundingBoxSize = value;
  69943. var scene = this.getScene();
  69944. if (scene) {
  69945. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69946. }
  69947. },
  69948. enumerable: true,
  69949. configurable: true
  69950. });
  69951. /**
  69952. * Creates a depth stencil texture.
  69953. * This is only available in WebGL 2 or with the depth texture extension available.
  69954. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69955. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69956. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69957. */
  69958. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69959. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69960. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69961. if (generateStencil === void 0) { generateStencil = false; }
  69962. if (!this.getScene()) {
  69963. return;
  69964. }
  69965. var engine = this.getScene().getEngine();
  69966. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69967. bilinearFiltering: bilinearFiltering,
  69968. comparisonFunction: comparisonFunction,
  69969. generateStencil: generateStencil,
  69970. isCube: this.isCube
  69971. });
  69972. engine.setFrameBufferDepthStencilTexture(this);
  69973. };
  69974. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69975. if (size.ratio) {
  69976. this._sizeRatio = size.ratio;
  69977. this._size = {
  69978. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69979. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69980. };
  69981. }
  69982. else {
  69983. this._size = size;
  69984. }
  69985. };
  69986. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69987. get: function () {
  69988. return this._samples;
  69989. },
  69990. set: function (value) {
  69991. if (this._samples === value) {
  69992. return;
  69993. }
  69994. var scene = this.getScene();
  69995. if (!scene) {
  69996. return;
  69997. }
  69998. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69999. },
  70000. enumerable: true,
  70001. configurable: true
  70002. });
  70003. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  70004. this._currentRefreshId = -1;
  70005. };
  70006. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  70007. get: function () {
  70008. return this._refreshRate;
  70009. },
  70010. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70011. set: function (value) {
  70012. this._refreshRate = value;
  70013. this.resetRefreshCounter();
  70014. },
  70015. enumerable: true,
  70016. configurable: true
  70017. });
  70018. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  70019. if (!this._postProcessManager) {
  70020. var scene = this.getScene();
  70021. if (!scene) {
  70022. return;
  70023. }
  70024. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  70025. this._postProcesses = new Array();
  70026. }
  70027. this._postProcesses.push(postProcess);
  70028. this._postProcesses[0].autoClear = false;
  70029. };
  70030. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  70031. if (!this._postProcesses) {
  70032. return;
  70033. }
  70034. if (dispose) {
  70035. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  70036. var postProcess = _a[_i];
  70037. postProcess.dispose();
  70038. }
  70039. }
  70040. this._postProcesses = [];
  70041. };
  70042. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  70043. if (!this._postProcesses) {
  70044. return;
  70045. }
  70046. var index = this._postProcesses.indexOf(postProcess);
  70047. if (index === -1) {
  70048. return;
  70049. }
  70050. this._postProcesses.splice(index, 1);
  70051. if (this._postProcesses.length > 0) {
  70052. this._postProcesses[0].autoClear = false;
  70053. }
  70054. };
  70055. /** @hidden */
  70056. RenderTargetTexture.prototype._shouldRender = function () {
  70057. if (this._currentRefreshId === -1) { // At least render once
  70058. this._currentRefreshId = 1;
  70059. return true;
  70060. }
  70061. if (this.refreshRate === this._currentRefreshId) {
  70062. this._currentRefreshId = 1;
  70063. return true;
  70064. }
  70065. this._currentRefreshId++;
  70066. return false;
  70067. };
  70068. RenderTargetTexture.prototype.getRenderSize = function () {
  70069. if (this._size.width) {
  70070. return this._size.width;
  70071. }
  70072. return this._size;
  70073. };
  70074. RenderTargetTexture.prototype.getRenderWidth = function () {
  70075. if (this._size.width) {
  70076. return this._size.width;
  70077. }
  70078. return this._size;
  70079. };
  70080. RenderTargetTexture.prototype.getRenderHeight = function () {
  70081. if (this._size.width) {
  70082. return this._size.height;
  70083. }
  70084. return this._size;
  70085. };
  70086. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  70087. get: function () {
  70088. return true;
  70089. },
  70090. enumerable: true,
  70091. configurable: true
  70092. });
  70093. RenderTargetTexture.prototype.scale = function (ratio) {
  70094. var newSize = this.getRenderSize() * ratio;
  70095. this.resize(newSize);
  70096. };
  70097. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  70098. if (this.isCube) {
  70099. return this._textureMatrix;
  70100. }
  70101. return _super.prototype.getReflectionTextureMatrix.call(this);
  70102. };
  70103. RenderTargetTexture.prototype.resize = function (size) {
  70104. this.releaseInternalTexture();
  70105. var scene = this.getScene();
  70106. if (!scene) {
  70107. return;
  70108. }
  70109. this._processSizeParameter(size);
  70110. if (this.isCube) {
  70111. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  70112. }
  70113. else {
  70114. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  70115. }
  70116. };
  70117. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  70118. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  70119. if (dumpForDebug === void 0) { dumpForDebug = false; }
  70120. var scene = this.getScene();
  70121. if (!scene) {
  70122. return;
  70123. }
  70124. var engine = scene.getEngine();
  70125. if (this.useCameraPostProcesses !== undefined) {
  70126. useCameraPostProcess = this.useCameraPostProcesses;
  70127. }
  70128. if (this._waitingRenderList) {
  70129. this.renderList = [];
  70130. for (var index = 0; index < this._waitingRenderList.length; index++) {
  70131. var id = this._waitingRenderList[index];
  70132. var mesh_1 = scene.getMeshByID(id);
  70133. if (mesh_1) {
  70134. this.renderList.push(mesh_1);
  70135. }
  70136. }
  70137. delete this._waitingRenderList;
  70138. }
  70139. // Is predicate defined?
  70140. if (this.renderListPredicate) {
  70141. if (this.renderList) {
  70142. this.renderList.splice(0); // Clear previous renderList
  70143. }
  70144. else {
  70145. this.renderList = [];
  70146. }
  70147. var scene = this.getScene();
  70148. if (!scene) {
  70149. return;
  70150. }
  70151. var sceneMeshes = scene.meshes;
  70152. for (var index = 0; index < sceneMeshes.length; index++) {
  70153. var mesh = sceneMeshes[index];
  70154. if (this.renderListPredicate(mesh)) {
  70155. this.renderList.push(mesh);
  70156. }
  70157. }
  70158. }
  70159. this.onBeforeBindObservable.notifyObservers(this);
  70160. // Set custom projection.
  70161. // Needs to be before binding to prevent changing the aspect ratio.
  70162. var camera;
  70163. if (this.activeCamera) {
  70164. camera = this.activeCamera;
  70165. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70166. if (this.activeCamera !== scene.activeCamera) {
  70167. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  70168. }
  70169. }
  70170. else {
  70171. camera = scene.activeCamera;
  70172. if (camera) {
  70173. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  70174. }
  70175. }
  70176. // Prepare renderingManager
  70177. this._renderingManager.reset();
  70178. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  70179. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  70180. var sceneRenderId = scene.getRenderId();
  70181. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  70182. var mesh = currentRenderList[meshIndex];
  70183. if (mesh) {
  70184. if (!mesh.isReady(this.refreshRate === 0)) {
  70185. this.resetRefreshCounter();
  70186. continue;
  70187. }
  70188. mesh._preActivateForIntermediateRendering(sceneRenderId);
  70189. var isMasked = void 0;
  70190. if (!this.renderList && camera) {
  70191. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  70192. }
  70193. else {
  70194. isMasked = false;
  70195. }
  70196. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  70197. mesh._activate(sceneRenderId);
  70198. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  70199. var subMesh = mesh.subMeshes[subIndex];
  70200. scene._activeIndices.addCount(subMesh.indexCount, false);
  70201. this._renderingManager.dispatch(subMesh, mesh);
  70202. }
  70203. }
  70204. }
  70205. }
  70206. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  70207. var particleSystem = scene.particleSystems[particleIndex];
  70208. var emitter = particleSystem.emitter;
  70209. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  70210. continue;
  70211. }
  70212. if (currentRenderList.indexOf(emitter) >= 0) {
  70213. this._renderingManager.dispatchParticles(particleSystem);
  70214. }
  70215. }
  70216. if (this.isCube) {
  70217. for (var face = 0; face < 6; face++) {
  70218. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70219. scene.incrementRenderId();
  70220. scene.resetCachedMaterial();
  70221. }
  70222. }
  70223. else {
  70224. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  70225. }
  70226. this.onAfterUnbindObservable.notifyObservers(this);
  70227. if (scene.activeCamera) {
  70228. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  70229. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  70230. }
  70231. engine.setViewport(scene.activeCamera.viewport);
  70232. }
  70233. scene.resetCachedMaterial();
  70234. };
  70235. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  70236. var minimum = 128;
  70237. var x = renderDimension * scale;
  70238. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  70239. // Ensure we don't exceed the render dimension (while staying POT)
  70240. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  70241. };
  70242. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70243. var _this = this;
  70244. if (!this._texture) {
  70245. return;
  70246. }
  70247. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  70248. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70249. });
  70250. };
  70251. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  70252. var scene = this.getScene();
  70253. if (!scene) {
  70254. return;
  70255. }
  70256. var engine = scene.getEngine();
  70257. if (!this._texture) {
  70258. return;
  70259. }
  70260. // Bind
  70261. if (this._postProcessManager) {
  70262. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  70263. }
  70264. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  70265. if (this._texture) {
  70266. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  70267. }
  70268. }
  70269. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  70270. // Clear
  70271. if (this.onClearObservable.hasObservers()) {
  70272. this.onClearObservable.notifyObservers(engine);
  70273. }
  70274. else {
  70275. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  70276. }
  70277. if (!this._doNotChangeAspectRatio) {
  70278. scene.updateTransformMatrix(true);
  70279. }
  70280. // Render
  70281. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  70282. if (this._postProcessManager) {
  70283. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  70284. }
  70285. else if (useCameraPostProcess) {
  70286. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  70287. }
  70288. if (!this._doNotChangeAspectRatio) {
  70289. scene.updateTransformMatrix(true);
  70290. }
  70291. // Dump ?
  70292. if (dumpForDebug) {
  70293. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  70294. }
  70295. // Unbind
  70296. if (!this.isCube || faceIndex === 5) {
  70297. if (this.isCube) {
  70298. if (faceIndex === 5) {
  70299. engine.generateMipMapsForCubemap(this._texture);
  70300. }
  70301. }
  70302. this.unbindFrameBuffer(engine, faceIndex);
  70303. }
  70304. else {
  70305. this.onAfterRenderObservable.notifyObservers(faceIndex);
  70306. }
  70307. };
  70308. /**
  70309. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  70310. * This allowed control for front to back rendering or reversly depending of the special needs.
  70311. *
  70312. * @param renderingGroupId The rendering group id corresponding to its index
  70313. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  70314. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  70315. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  70316. */
  70317. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  70318. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  70319. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  70320. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  70321. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  70322. };
  70323. /**
  70324. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70325. *
  70326. * @param renderingGroupId The rendering group id corresponding to its index
  70327. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70328. */
  70329. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70330. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70331. this._renderingManager._useSceneAutoClearSetup = false;
  70332. };
  70333. RenderTargetTexture.prototype.clone = function () {
  70334. var textureSize = this.getSize();
  70335. 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);
  70336. // Base texture
  70337. newTexture.hasAlpha = this.hasAlpha;
  70338. newTexture.level = this.level;
  70339. // RenderTarget Texture
  70340. newTexture.coordinatesMode = this.coordinatesMode;
  70341. if (this.renderList) {
  70342. newTexture.renderList = this.renderList.slice(0);
  70343. }
  70344. return newTexture;
  70345. };
  70346. RenderTargetTexture.prototype.serialize = function () {
  70347. if (!this.name) {
  70348. return null;
  70349. }
  70350. var serializationObject = _super.prototype.serialize.call(this);
  70351. serializationObject.renderTargetSize = this.getRenderSize();
  70352. serializationObject.renderList = [];
  70353. if (this.renderList) {
  70354. for (var index = 0; index < this.renderList.length; index++) {
  70355. serializationObject.renderList.push(this.renderList[index].id);
  70356. }
  70357. }
  70358. return serializationObject;
  70359. };
  70360. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  70361. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  70362. var objBuffer = this.getInternalTexture();
  70363. var scene = this.getScene();
  70364. if (objBuffer && scene) {
  70365. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  70366. }
  70367. };
  70368. RenderTargetTexture.prototype.dispose = function () {
  70369. if (this._postProcessManager) {
  70370. this._postProcessManager.dispose();
  70371. this._postProcessManager = null;
  70372. }
  70373. this.clearPostProcesses(true);
  70374. if (this._resizeObserver) {
  70375. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  70376. this._resizeObserver = null;
  70377. }
  70378. this.renderList = null;
  70379. // Remove from custom render targets
  70380. var scene = this.getScene();
  70381. if (!scene) {
  70382. return;
  70383. }
  70384. var index = scene.customRenderTargets.indexOf(this);
  70385. if (index >= 0) {
  70386. scene.customRenderTargets.splice(index, 1);
  70387. }
  70388. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  70389. var camera = _a[_i];
  70390. index = camera.customRenderTargets.indexOf(this);
  70391. if (index >= 0) {
  70392. camera.customRenderTargets.splice(index, 1);
  70393. }
  70394. }
  70395. _super.prototype.dispose.call(this);
  70396. };
  70397. /** @hidden */
  70398. RenderTargetTexture.prototype._rebuild = function () {
  70399. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70400. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70401. }
  70402. if (this._postProcessManager) {
  70403. this._postProcessManager._rebuild();
  70404. }
  70405. };
  70406. /**
  70407. * Clear the info related to rendering groups preventing retention point in material dispose.
  70408. */
  70409. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  70410. if (this._renderingManager) {
  70411. this._renderingManager.freeRenderingGroups();
  70412. }
  70413. };
  70414. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  70415. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  70416. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  70417. return RenderTargetTexture;
  70418. }(BABYLON.Texture));
  70419. BABYLON.RenderTargetTexture = RenderTargetTexture;
  70420. })(BABYLON || (BABYLON = {}));
  70421. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  70422. var BABYLON;
  70423. (function (BABYLON) {
  70424. ;
  70425. var MultiRenderTarget = /** @class */ (function (_super) {
  70426. __extends(MultiRenderTarget, _super);
  70427. function MultiRenderTarget(name, size, count, scene, options) {
  70428. var _this = this;
  70429. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  70430. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  70431. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  70432. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  70433. _this._engine = scene.getEngine();
  70434. if (!_this.isSupported) {
  70435. _this.dispose();
  70436. return;
  70437. }
  70438. var types = [];
  70439. var samplingModes = [];
  70440. for (var i = 0; i < count; i++) {
  70441. if (options && options.types && options.types[i] !== undefined) {
  70442. types.push(options.types[i]);
  70443. }
  70444. else {
  70445. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70446. }
  70447. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  70448. samplingModes.push(options.samplingModes[i]);
  70449. }
  70450. else {
  70451. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70452. }
  70453. }
  70454. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  70455. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  70456. _this._size = size;
  70457. _this._multiRenderTargetOptions = {
  70458. samplingModes: samplingModes,
  70459. generateMipMaps: generateMipMaps,
  70460. generateDepthBuffer: generateDepthBuffer,
  70461. generateStencilBuffer: generateStencilBuffer,
  70462. generateDepthTexture: generateDepthTexture,
  70463. types: types,
  70464. textureCount: count
  70465. };
  70466. _this._createInternalTextures();
  70467. _this._createTextures();
  70468. return _this;
  70469. }
  70470. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  70471. get: function () {
  70472. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  70473. },
  70474. enumerable: true,
  70475. configurable: true
  70476. });
  70477. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  70478. get: function () {
  70479. return this._textures;
  70480. },
  70481. enumerable: true,
  70482. configurable: true
  70483. });
  70484. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  70485. get: function () {
  70486. return this._textures[this._textures.length - 1];
  70487. },
  70488. enumerable: true,
  70489. configurable: true
  70490. });
  70491. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  70492. set: function (wrap) {
  70493. if (this._textures) {
  70494. for (var i = 0; i < this._textures.length; i++) {
  70495. this._textures[i].wrapU = wrap;
  70496. }
  70497. }
  70498. },
  70499. enumerable: true,
  70500. configurable: true
  70501. });
  70502. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  70503. set: function (wrap) {
  70504. if (this._textures) {
  70505. for (var i = 0; i < this._textures.length; i++) {
  70506. this._textures[i].wrapV = wrap;
  70507. }
  70508. }
  70509. },
  70510. enumerable: true,
  70511. configurable: true
  70512. });
  70513. /** @hidden */
  70514. MultiRenderTarget.prototype._rebuild = function () {
  70515. this.releaseInternalTextures();
  70516. this._createInternalTextures();
  70517. for (var i = 0; i < this._internalTextures.length; i++) {
  70518. var texture = this._textures[i];
  70519. texture._texture = this._internalTextures[i];
  70520. }
  70521. // Keeps references to frame buffer and stencil/depth buffer
  70522. this._texture = this._internalTextures[0];
  70523. };
  70524. MultiRenderTarget.prototype._createInternalTextures = function () {
  70525. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  70526. };
  70527. MultiRenderTarget.prototype._createTextures = function () {
  70528. this._textures = [];
  70529. for (var i = 0; i < this._internalTextures.length; i++) {
  70530. var texture = new BABYLON.Texture(null, this.getScene());
  70531. texture._texture = this._internalTextures[i];
  70532. this._textures.push(texture);
  70533. }
  70534. // Keeps references to frame buffer and stencil/depth buffer
  70535. this._texture = this._internalTextures[0];
  70536. };
  70537. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  70538. get: function () {
  70539. return this._samples;
  70540. },
  70541. set: function (value) {
  70542. if (this._samples === value) {
  70543. return;
  70544. }
  70545. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  70546. },
  70547. enumerable: true,
  70548. configurable: true
  70549. });
  70550. MultiRenderTarget.prototype.resize = function (size) {
  70551. this.releaseInternalTextures();
  70552. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  70553. this._createInternalTextures();
  70554. };
  70555. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  70556. var _this = this;
  70557. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  70558. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  70559. });
  70560. };
  70561. MultiRenderTarget.prototype.dispose = function () {
  70562. this.releaseInternalTextures();
  70563. _super.prototype.dispose.call(this);
  70564. };
  70565. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  70566. if (!this._internalTextures) {
  70567. return;
  70568. }
  70569. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  70570. if (this._internalTextures[i] !== undefined) {
  70571. this._internalTextures[i].dispose();
  70572. this._internalTextures.splice(i, 1);
  70573. }
  70574. }
  70575. };
  70576. return MultiRenderTarget;
  70577. }(BABYLON.RenderTargetTexture));
  70578. BABYLON.MultiRenderTarget = MultiRenderTarget;
  70579. })(BABYLON || (BABYLON = {}));
  70580. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  70581. var BABYLON;
  70582. (function (BABYLON) {
  70583. var MirrorTexture = /** @class */ (function (_super) {
  70584. __extends(MirrorTexture, _super);
  70585. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  70586. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70588. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70589. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  70590. _this.scene = scene;
  70591. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  70592. _this._transformMatrix = BABYLON.Matrix.Zero();
  70593. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  70594. _this._adaptiveBlurKernel = 0;
  70595. _this._blurKernelX = 0;
  70596. _this._blurKernelY = 0;
  70597. _this._blurRatio = 1.0;
  70598. _this.ignoreCameraViewport = true;
  70599. _this._updateGammaSpace();
  70600. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70601. _this._updateGammaSpace;
  70602. });
  70603. _this.onBeforeRenderObservable.add(function () {
  70604. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  70605. _this._savedViewMatrix = scene.getViewMatrix();
  70606. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  70607. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  70608. scene.clipPlane = _this.mirrorPlane;
  70609. scene.getEngine().cullBackFaces = false;
  70610. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  70611. });
  70612. _this.onAfterRenderObservable.add(function () {
  70613. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  70614. scene.getEngine().cullBackFaces = true;
  70615. scene._mirroredCameraPosition = null;
  70616. delete scene.clipPlane;
  70617. });
  70618. return _this;
  70619. }
  70620. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  70621. get: function () {
  70622. return this._blurRatio;
  70623. },
  70624. set: function (value) {
  70625. if (this._blurRatio === value) {
  70626. return;
  70627. }
  70628. this._blurRatio = value;
  70629. this._preparePostProcesses();
  70630. },
  70631. enumerable: true,
  70632. configurable: true
  70633. });
  70634. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  70635. set: function (value) {
  70636. this._adaptiveBlurKernel = value;
  70637. this._autoComputeBlurKernel();
  70638. },
  70639. enumerable: true,
  70640. configurable: true
  70641. });
  70642. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  70643. set: function (value) {
  70644. this.blurKernelX = value;
  70645. this.blurKernelY = value;
  70646. },
  70647. enumerable: true,
  70648. configurable: true
  70649. });
  70650. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  70651. get: function () {
  70652. return this._blurKernelX;
  70653. },
  70654. set: function (value) {
  70655. if (this._blurKernelX === value) {
  70656. return;
  70657. }
  70658. this._blurKernelX = value;
  70659. this._preparePostProcesses();
  70660. },
  70661. enumerable: true,
  70662. configurable: true
  70663. });
  70664. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  70665. get: function () {
  70666. return this._blurKernelY;
  70667. },
  70668. set: function (value) {
  70669. if (this._blurKernelY === value) {
  70670. return;
  70671. }
  70672. this._blurKernelY = value;
  70673. this._preparePostProcesses();
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  70679. var engine = this.getScene().getEngine();
  70680. var dw = this.getRenderWidth() / engine.getRenderWidth();
  70681. var dh = this.getRenderHeight() / engine.getRenderHeight();
  70682. this.blurKernelX = this._adaptiveBlurKernel * dw;
  70683. this.blurKernelY = this._adaptiveBlurKernel * dh;
  70684. };
  70685. MirrorTexture.prototype._onRatioRescale = function () {
  70686. if (this._sizeRatio) {
  70687. this.resize(this._initialSizeParameter);
  70688. if (!this._adaptiveBlurKernel) {
  70689. this._preparePostProcesses();
  70690. }
  70691. }
  70692. if (this._adaptiveBlurKernel) {
  70693. this._autoComputeBlurKernel();
  70694. }
  70695. };
  70696. MirrorTexture.prototype._updateGammaSpace = function () {
  70697. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  70698. };
  70699. MirrorTexture.prototype._preparePostProcesses = function () {
  70700. this.clearPostProcesses(true);
  70701. if (this._blurKernelX && this._blurKernelY) {
  70702. var engine = this.getScene().getEngine();
  70703. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70704. 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);
  70705. this._blurX.autoClear = false;
  70706. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70707. this._blurX.inputTexture = this._texture;
  70708. }
  70709. else {
  70710. this._blurX.alwaysForcePOT = true;
  70711. }
  70712. 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);
  70713. this._blurY.autoClear = false;
  70714. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70715. this.addPostProcess(this._blurX);
  70716. this.addPostProcess(this._blurY);
  70717. }
  70718. else {
  70719. if (this._blurY) {
  70720. this.removePostProcess(this._blurY);
  70721. this._blurY.dispose();
  70722. this._blurY = null;
  70723. }
  70724. if (this._blurX) {
  70725. this.removePostProcess(this._blurX);
  70726. this._blurX.dispose();
  70727. this._blurX = null;
  70728. }
  70729. }
  70730. };
  70731. MirrorTexture.prototype.clone = function () {
  70732. var scene = this.getScene();
  70733. if (!scene) {
  70734. return this;
  70735. }
  70736. var textureSize = this.getSize();
  70737. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70738. // Base texture
  70739. newTexture.hasAlpha = this.hasAlpha;
  70740. newTexture.level = this.level;
  70741. // Mirror Texture
  70742. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70743. if (this.renderList) {
  70744. newTexture.renderList = this.renderList.slice(0);
  70745. }
  70746. return newTexture;
  70747. };
  70748. MirrorTexture.prototype.serialize = function () {
  70749. if (!this.name) {
  70750. return null;
  70751. }
  70752. var serializationObject = _super.prototype.serialize.call(this);
  70753. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70754. return serializationObject;
  70755. };
  70756. MirrorTexture.prototype.dispose = function () {
  70757. _super.prototype.dispose.call(this);
  70758. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70759. };
  70760. return MirrorTexture;
  70761. }(BABYLON.RenderTargetTexture));
  70762. BABYLON.MirrorTexture = MirrorTexture;
  70763. })(BABYLON || (BABYLON = {}));
  70764. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70765. var BABYLON;
  70766. (function (BABYLON) {
  70767. /**
  70768. * Creates a refraction texture used by refraction channel of the standard material.
  70769. * @param name the texture name
  70770. * @param size size of the underlying texture
  70771. * @param scene root scene
  70772. */
  70773. var RefractionTexture = /** @class */ (function (_super) {
  70774. __extends(RefractionTexture, _super);
  70775. function RefractionTexture(name, size, scene, generateMipMaps) {
  70776. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70777. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70778. _this.depth = 2.0;
  70779. _this.onBeforeRenderObservable.add(function () {
  70780. scene.clipPlane = _this.refractionPlane;
  70781. });
  70782. _this.onAfterRenderObservable.add(function () {
  70783. delete scene.clipPlane;
  70784. });
  70785. return _this;
  70786. }
  70787. RefractionTexture.prototype.clone = function () {
  70788. var scene = this.getScene();
  70789. if (!scene) {
  70790. return this;
  70791. }
  70792. var textureSize = this.getSize();
  70793. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70794. // Base texture
  70795. newTexture.hasAlpha = this.hasAlpha;
  70796. newTexture.level = this.level;
  70797. // Refraction Texture
  70798. newTexture.refractionPlane = this.refractionPlane.clone();
  70799. if (this.renderList) {
  70800. newTexture.renderList = this.renderList.slice(0);
  70801. }
  70802. newTexture.depth = this.depth;
  70803. return newTexture;
  70804. };
  70805. RefractionTexture.prototype.serialize = function () {
  70806. if (!this.name) {
  70807. return null;
  70808. }
  70809. var serializationObject = _super.prototype.serialize.call(this);
  70810. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70811. serializationObject.depth = this.depth;
  70812. return serializationObject;
  70813. };
  70814. return RefractionTexture;
  70815. }(BABYLON.RenderTargetTexture));
  70816. BABYLON.RefractionTexture = RefractionTexture;
  70817. })(BABYLON || (BABYLON = {}));
  70818. //# sourceMappingURL=babylon.refractionTexture.js.map
  70819. var BABYLON;
  70820. (function (BABYLON) {
  70821. /**
  70822. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70823. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70824. */
  70825. var DynamicTexture = /** @class */ (function (_super) {
  70826. __extends(DynamicTexture, _super);
  70827. /**
  70828. * Creates a {BABYLON.DynamicTexture}
  70829. * @param name defines the name of the texture
  70830. * @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
  70831. * @param scene defines the scene where you want the texture
  70832. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70833. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70834. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70835. */
  70836. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70837. if (scene === void 0) { scene = null; }
  70838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70839. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70840. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70841. _this.name = name;
  70842. _this._engine = _this.getScene().getEngine();
  70843. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70844. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70845. _this._generateMipMaps = generateMipMaps;
  70846. if (options.getContext) {
  70847. _this._canvas = options;
  70848. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70849. }
  70850. else {
  70851. _this._canvas = document.createElement("canvas");
  70852. if (options.width || options.width === 0) {
  70853. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70854. }
  70855. else {
  70856. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70857. }
  70858. }
  70859. var textureSize = _this.getSize();
  70860. _this._canvas.width = textureSize.width;
  70861. _this._canvas.height = textureSize.height;
  70862. _this._context = _this._canvas.getContext("2d");
  70863. return _this;
  70864. }
  70865. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70866. /**
  70867. * Gets the current state of canRescale
  70868. */
  70869. get: function () {
  70870. return true;
  70871. },
  70872. enumerable: true,
  70873. configurable: true
  70874. });
  70875. DynamicTexture.prototype._recreate = function (textureSize) {
  70876. this._canvas.width = textureSize.width;
  70877. this._canvas.height = textureSize.height;
  70878. this.releaseInternalTexture();
  70879. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70880. };
  70881. /**
  70882. * Scales the texture
  70883. * @param ratio the scale factor to apply to both width and height
  70884. */
  70885. DynamicTexture.prototype.scale = function (ratio) {
  70886. var textureSize = this.getSize();
  70887. textureSize.width *= ratio;
  70888. textureSize.height *= ratio;
  70889. this._recreate(textureSize);
  70890. };
  70891. /**
  70892. * Resizes the texture
  70893. * @param width the new width
  70894. * @param height the new height
  70895. */
  70896. DynamicTexture.prototype.scaleTo = function (width, height) {
  70897. var textureSize = this.getSize();
  70898. textureSize.width = width;
  70899. textureSize.height = height;
  70900. this._recreate(textureSize);
  70901. };
  70902. /**
  70903. * Gets the context of the canvas used by the texture
  70904. * @returns the canvas context of the dynamic texture
  70905. */
  70906. DynamicTexture.prototype.getContext = function () {
  70907. return this._context;
  70908. };
  70909. /**
  70910. * Clears the texture
  70911. */
  70912. DynamicTexture.prototype.clear = function () {
  70913. var size = this.getSize();
  70914. this._context.fillRect(0, 0, size.width, size.height);
  70915. };
  70916. /**
  70917. * Updates the texture
  70918. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70919. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70920. */
  70921. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70922. if (premulAlpha === void 0) { premulAlpha = false; }
  70923. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70924. };
  70925. /**
  70926. * Draws text onto the texture
  70927. * @param text defines the text to be drawn
  70928. * @param x defines the placement of the text from the left
  70929. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70930. * @param font defines the font to be used with font-style, font-size, font-name
  70931. * @param color defines the color used for the text
  70932. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70933. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70934. * @param update defines whether texture is immediately update (default is true)
  70935. */
  70936. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70937. if (update === void 0) { update = true; }
  70938. var size = this.getSize();
  70939. if (clearColor) {
  70940. this._context.fillStyle = clearColor;
  70941. this._context.fillRect(0, 0, size.width, size.height);
  70942. }
  70943. this._context.font = font;
  70944. if (x === null || x === undefined) {
  70945. var textSize = this._context.measureText(text);
  70946. x = (size.width - textSize.width) / 2;
  70947. }
  70948. if (y === null || y === undefined) {
  70949. var fontSize = parseInt((font.replace(/\D/g, '')));
  70950. y = (size.height / 2) + (fontSize / 3.65);
  70951. }
  70952. this._context.fillStyle = color;
  70953. this._context.fillText(text, x, y);
  70954. if (update) {
  70955. this.update(invertY);
  70956. }
  70957. };
  70958. /**
  70959. * Clones the texture
  70960. * @returns the clone of the texture.
  70961. */
  70962. DynamicTexture.prototype.clone = function () {
  70963. var scene = this.getScene();
  70964. if (!scene) {
  70965. return this;
  70966. }
  70967. var textureSize = this.getSize();
  70968. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70969. // Base texture
  70970. newTexture.hasAlpha = this.hasAlpha;
  70971. newTexture.level = this.level;
  70972. // Dynamic Texture
  70973. newTexture.wrapU = this.wrapU;
  70974. newTexture.wrapV = this.wrapV;
  70975. return newTexture;
  70976. };
  70977. /**
  70978. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70979. * @returns a serialized dynamic texture object
  70980. */
  70981. DynamicTexture.prototype.serialize = function () {
  70982. var scene = this.getScene();
  70983. if (scene && !scene.isReady()) {
  70984. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70985. }
  70986. var serializationObject = _super.prototype.serialize.call(this);
  70987. serializationObject.base64String = this._canvas.toDataURL();
  70988. serializationObject.invertY = this._invertY;
  70989. serializationObject.samplingMode = this.samplingMode;
  70990. return serializationObject;
  70991. };
  70992. /** @hidden */
  70993. DynamicTexture.prototype._rebuild = function () {
  70994. this.update();
  70995. };
  70996. return DynamicTexture;
  70997. }(BABYLON.Texture));
  70998. BABYLON.DynamicTexture = DynamicTexture;
  70999. })(BABYLON || (BABYLON = {}));
  71000. //# sourceMappingURL=babylon.dynamicTexture.js.map
  71001. var BABYLON;
  71002. (function (BABYLON) {
  71003. var VideoTexture = /** @class */ (function (_super) {
  71004. __extends(VideoTexture, _super);
  71005. /**
  71006. * Creates a video texture.
  71007. * Sample : https://doc.babylonjs.com/how_to/video_texture
  71008. * @param {string | null} name optional name, will detect from video source, if not defined
  71009. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  71010. * @param {BABYLON.Scene} scene is obviously the current scene.
  71011. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  71012. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  71013. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  71014. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  71015. */
  71016. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  71017. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71018. if (invertY === void 0) { invertY = false; }
  71019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71020. if (settings === void 0) { settings = {
  71021. autoPlay: true,
  71022. loop: true,
  71023. autoUpdateTexture: true,
  71024. }; }
  71025. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71026. _this._onUserActionRequestedObservable = null;
  71027. _this._stillImageCaptured = false;
  71028. _this._poster = false;
  71029. _this._createInternalTexture = function () {
  71030. if (_this._texture != null) {
  71031. if (_this._poster) {
  71032. _this._texture.dispose();
  71033. _this._poster = false;
  71034. }
  71035. else {
  71036. return;
  71037. }
  71038. }
  71039. if (!_this._engine.needPOTTextures ||
  71040. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  71041. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71042. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71043. }
  71044. else {
  71045. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71046. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71047. _this._generateMipMaps = false;
  71048. }
  71049. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  71050. if (!_this.video.autoplay) {
  71051. var oldHandler_1 = _this.video.onplaying;
  71052. var error_1 = false;
  71053. _this.video.onplaying = function () {
  71054. _this.video.onplaying = oldHandler_1;
  71055. _this._texture.isReady = true;
  71056. _this._updateInternalTexture();
  71057. if (!error_1) {
  71058. _this.video.pause();
  71059. }
  71060. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71061. _this.onLoadObservable.notifyObservers(_this);
  71062. }
  71063. };
  71064. var playing = _this.video.play();
  71065. if (playing) {
  71066. playing.then(function () {
  71067. // Everything is good.
  71068. })
  71069. .catch(function () {
  71070. error_1 = true;
  71071. // On Chrome for instance, new policies might prevent playing without user interaction.
  71072. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  71073. _this._onUserActionRequestedObservable.notifyObservers(_this);
  71074. }
  71075. });
  71076. }
  71077. else {
  71078. _this.video.onplaying = oldHandler_1;
  71079. _this._texture.isReady = true;
  71080. _this._updateInternalTexture();
  71081. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71082. _this.onLoadObservable.notifyObservers(_this);
  71083. }
  71084. }
  71085. }
  71086. else {
  71087. _this._texture.isReady = true;
  71088. _this._updateInternalTexture();
  71089. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  71090. _this.onLoadObservable.notifyObservers(_this);
  71091. }
  71092. }
  71093. };
  71094. _this.reset = function () {
  71095. if (_this._texture == null) {
  71096. return;
  71097. }
  71098. if (!_this._poster) {
  71099. _this._texture.dispose();
  71100. _this._texture = null;
  71101. }
  71102. };
  71103. _this._updateInternalTexture = function (e) {
  71104. if (_this._texture == null || !_this._texture.isReady) {
  71105. return;
  71106. }
  71107. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  71108. return;
  71109. }
  71110. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  71111. };
  71112. _this._engine = _this.getScene().getEngine();
  71113. _this._generateMipMaps = generateMipMaps;
  71114. _this._samplingMode = samplingMode;
  71115. _this.autoUpdateTexture = settings.autoUpdateTexture;
  71116. _this.name = name || _this._getName(src);
  71117. _this.video = _this._getVideo(src);
  71118. if (settings.poster) {
  71119. _this.video.poster = settings.poster;
  71120. }
  71121. if (settings.autoPlay !== undefined) {
  71122. _this.video.autoplay = settings.autoPlay;
  71123. }
  71124. if (settings.loop !== undefined) {
  71125. _this.video.loop = settings.loop;
  71126. }
  71127. _this.video.setAttribute("playsinline", "");
  71128. _this.video.addEventListener("canplay", _this._createInternalTexture);
  71129. _this.video.addEventListener("paused", _this._updateInternalTexture);
  71130. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  71131. _this.video.addEventListener("emptied", _this.reset);
  71132. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  71133. _this._createInternalTexture();
  71134. }
  71135. if (settings.poster) {
  71136. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  71137. _this._poster = true;
  71138. }
  71139. return _this;
  71140. }
  71141. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  71142. get: function () {
  71143. if (!this._onUserActionRequestedObservable) {
  71144. this._onUserActionRequestedObservable = new BABYLON.Observable();
  71145. }
  71146. return this._onUserActionRequestedObservable;
  71147. },
  71148. enumerable: true,
  71149. configurable: true
  71150. });
  71151. VideoTexture.prototype._getName = function (src) {
  71152. if (src instanceof HTMLVideoElement) {
  71153. return src.currentSrc;
  71154. }
  71155. if (typeof src === "object") {
  71156. return src.toString();
  71157. }
  71158. return src;
  71159. };
  71160. ;
  71161. VideoTexture.prototype._getVideo = function (src) {
  71162. if (src instanceof HTMLVideoElement) {
  71163. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  71164. return src;
  71165. }
  71166. var video = document.createElement("video");
  71167. if (typeof src === "string") {
  71168. BABYLON.Tools.SetCorsBehavior(src, video);
  71169. video.src = src;
  71170. }
  71171. else {
  71172. BABYLON.Tools.SetCorsBehavior(src[0], video);
  71173. src.forEach(function (url) {
  71174. var source = document.createElement("source");
  71175. source.src = url;
  71176. video.appendChild(source);
  71177. });
  71178. }
  71179. return video;
  71180. };
  71181. ;
  71182. /**
  71183. * @hidden Internal method to initiate `update`.
  71184. */
  71185. VideoTexture.prototype._rebuild = function () {
  71186. this.update();
  71187. };
  71188. /**
  71189. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  71190. */
  71191. VideoTexture.prototype.update = function () {
  71192. if (!this.autoUpdateTexture) {
  71193. // Expecting user to call `updateTexture` manually
  71194. return;
  71195. }
  71196. this.updateTexture(true);
  71197. };
  71198. /**
  71199. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  71200. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  71201. */
  71202. VideoTexture.prototype.updateTexture = function (isVisible) {
  71203. if (!isVisible) {
  71204. return;
  71205. }
  71206. if (this.video.paused && this._stillImageCaptured) {
  71207. return;
  71208. }
  71209. this._stillImageCaptured = true;
  71210. this._updateInternalTexture();
  71211. };
  71212. /**
  71213. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  71214. * @param url New url.
  71215. */
  71216. VideoTexture.prototype.updateURL = function (url) {
  71217. this.video.src = url;
  71218. };
  71219. VideoTexture.prototype.dispose = function () {
  71220. _super.prototype.dispose.call(this);
  71221. if (this._onUserActionRequestedObservable) {
  71222. this._onUserActionRequestedObservable.clear();
  71223. this._onUserActionRequestedObservable = null;
  71224. }
  71225. this.video.removeEventListener("canplay", this._createInternalTexture);
  71226. this.video.removeEventListener("paused", this._updateInternalTexture);
  71227. this.video.removeEventListener("seeked", this._updateInternalTexture);
  71228. this.video.removeEventListener("emptied", this.reset);
  71229. this.video.pause();
  71230. };
  71231. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  71232. var video = document.createElement("video");
  71233. video.setAttribute('autoplay', '');
  71234. video.setAttribute('muted', '');
  71235. video.setAttribute('playsinline', '');
  71236. var constraintsDeviceId;
  71237. if (constraints && constraints.deviceId) {
  71238. constraintsDeviceId = {
  71239. exact: constraints.deviceId,
  71240. };
  71241. }
  71242. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  71243. if (navigator.mediaDevices) {
  71244. navigator.mediaDevices.getUserMedia({ video: constraints })
  71245. .then(function (stream) {
  71246. if (video.mozSrcObject !== undefined) {
  71247. // hack for Firefox < 19
  71248. video.mozSrcObject = stream;
  71249. }
  71250. else {
  71251. video.srcObject = stream;
  71252. }
  71253. var onPlaying = function () {
  71254. if (onReady) {
  71255. onReady(new VideoTexture("video", video, scene, true, true));
  71256. }
  71257. video.removeEventListener("playing", onPlaying);
  71258. };
  71259. video.addEventListener("playing", onPlaying);
  71260. video.play();
  71261. })
  71262. .catch(function (err) {
  71263. BABYLON.Tools.Error(err.name);
  71264. });
  71265. }
  71266. else {
  71267. navigator.getUserMedia =
  71268. navigator.getUserMedia ||
  71269. navigator.webkitGetUserMedia ||
  71270. navigator.mozGetUserMedia ||
  71271. navigator.msGetUserMedia;
  71272. if (navigator.getUserMedia) {
  71273. navigator.getUserMedia({
  71274. video: {
  71275. deviceId: constraintsDeviceId,
  71276. width: {
  71277. min: (constraints && constraints.minWidth) || 256,
  71278. max: (constraints && constraints.maxWidth) || 640,
  71279. },
  71280. height: {
  71281. min: (constraints && constraints.minHeight) || 256,
  71282. max: (constraints && constraints.maxHeight) || 480,
  71283. },
  71284. },
  71285. }, function (stream) {
  71286. if (video.mozSrcObject !== undefined) {
  71287. // hack for Firefox < 19
  71288. video.mozSrcObject = stream;
  71289. }
  71290. else {
  71291. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  71292. }
  71293. video.play();
  71294. if (onReady) {
  71295. onReady(new VideoTexture("video", video, scene, true, true));
  71296. }
  71297. }, function (e) {
  71298. BABYLON.Tools.Error(e.name);
  71299. });
  71300. }
  71301. }
  71302. };
  71303. return VideoTexture;
  71304. }(BABYLON.Texture));
  71305. BABYLON.VideoTexture = VideoTexture;
  71306. })(BABYLON || (BABYLON = {}));
  71307. //# sourceMappingURL=babylon.videoTexture.js.map
  71308. var BABYLON;
  71309. (function (BABYLON) {
  71310. var RawTexture = /** @class */ (function (_super) {
  71311. __extends(RawTexture, _super);
  71312. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  71313. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71314. if (invertY === void 0) { invertY = false; }
  71315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71316. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71317. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71318. _this.format = format;
  71319. _this._engine = scene.getEngine();
  71320. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  71321. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71322. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71323. return _this;
  71324. }
  71325. RawTexture.prototype.update = function (data) {
  71326. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71327. };
  71328. // Statics
  71329. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71330. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71331. if (invertY === void 0) { invertY = false; }
  71332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71333. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  71334. };
  71335. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71336. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71337. if (invertY === void 0) { invertY = false; }
  71338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71339. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71340. };
  71341. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  71342. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71343. if (invertY === void 0) { invertY = false; }
  71344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71345. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  71346. };
  71347. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71348. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71349. if (invertY === void 0) { invertY = false; }
  71350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71351. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71352. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  71353. };
  71354. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71355. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71356. if (invertY === void 0) { invertY = false; }
  71357. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71358. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71359. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  71360. };
  71361. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  71362. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71363. if (invertY === void 0) { invertY = false; }
  71364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71365. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71366. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  71367. };
  71368. return RawTexture;
  71369. }(BABYLON.Texture));
  71370. BABYLON.RawTexture = RawTexture;
  71371. })(BABYLON || (BABYLON = {}));
  71372. //# sourceMappingURL=babylon.rawTexture.js.map
  71373. var BABYLON;
  71374. (function (BABYLON) {
  71375. /**
  71376. * Class used to store 3D textures containing user data
  71377. */
  71378. var RawTexture3D = /** @class */ (function (_super) {
  71379. __extends(RawTexture3D, _super);
  71380. /**
  71381. * Create a new RawTexture3D
  71382. * @param data defines the data of the texture
  71383. * @param width defines the width of the texture
  71384. * @param height defines the height of the texture
  71385. * @param depth defines the depth of the texture
  71386. * @param format defines the texture format to use
  71387. * @param scene defines the hosting scene
  71388. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  71389. * @param invertY defines if texture must be stored with Y axis inverted
  71390. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  71391. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  71392. */
  71393. function RawTexture3D(data, width, height, depth,
  71394. /** Gets or sets the texture format to use */
  71395. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  71396. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71397. if (invertY === void 0) { invertY = false; }
  71398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71399. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71400. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  71401. _this.format = format;
  71402. _this._engine = scene.getEngine();
  71403. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  71404. _this.is3D = true;
  71405. return _this;
  71406. }
  71407. /**
  71408. * Update the texture with new data
  71409. * @param data defines the data to store in the texture
  71410. */
  71411. RawTexture3D.prototype.update = function (data) {
  71412. if (!this._texture) {
  71413. return;
  71414. }
  71415. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  71416. };
  71417. return RawTexture3D;
  71418. }(BABYLON.Texture));
  71419. BABYLON.RawTexture3D = RawTexture3D;
  71420. })(BABYLON || (BABYLON = {}));
  71421. //# sourceMappingURL=babylon.rawTexture3D.js.map
  71422. var BABYLON;
  71423. (function (BABYLON) {
  71424. /**
  71425. * PostProcessManager is used to manage one or more post processes or post process pipelines
  71426. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71427. */
  71428. var PostProcessManager = /** @class */ (function () {
  71429. /**
  71430. * Creates a new instance PostProcess
  71431. * @param scene The scene that the post process is associated with.
  71432. */
  71433. function PostProcessManager(scene) {
  71434. this._vertexBuffers = {};
  71435. this._scene = scene;
  71436. }
  71437. PostProcessManager.prototype._prepareBuffers = function () {
  71438. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  71439. return;
  71440. }
  71441. // VBO
  71442. var vertices = [];
  71443. vertices.push(1, 1);
  71444. vertices.push(-1, 1);
  71445. vertices.push(-1, -1);
  71446. vertices.push(1, -1);
  71447. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71448. this._buildIndexBuffer();
  71449. };
  71450. PostProcessManager.prototype._buildIndexBuffer = function () {
  71451. // Indices
  71452. var indices = [];
  71453. indices.push(0);
  71454. indices.push(1);
  71455. indices.push(2);
  71456. indices.push(0);
  71457. indices.push(2);
  71458. indices.push(3);
  71459. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  71460. };
  71461. /**
  71462. * Rebuilds the vertex buffers of the manager.
  71463. * @hidden
  71464. */
  71465. PostProcessManager.prototype._rebuild = function () {
  71466. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71467. if (!vb) {
  71468. return;
  71469. }
  71470. vb._rebuild();
  71471. this._buildIndexBuffer();
  71472. };
  71473. // Methods
  71474. /**
  71475. * Prepares a frame to be run through a post process.
  71476. * @param sourceTexture The input texture to the post procesess. (default: null)
  71477. * @param postProcesses An array of post processes to be run. (default: null)
  71478. * @returns True if the post processes were able to be run.
  71479. * @hidden
  71480. */
  71481. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  71482. if (sourceTexture === void 0) { sourceTexture = null; }
  71483. if (postProcesses === void 0) { postProcesses = null; }
  71484. var camera = this._scene.activeCamera;
  71485. if (!camera) {
  71486. return false;
  71487. }
  71488. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71489. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71490. return false;
  71491. }
  71492. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  71493. return true;
  71494. };
  71495. /**
  71496. * Manually render a set of post processes to a texture.
  71497. * @param postProcesses An array of post processes to be run.
  71498. * @param targetTexture The target texture to render to.
  71499. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  71500. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  71501. * @param lodLevel defines which lod of the texture to render to
  71502. */
  71503. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  71504. if (targetTexture === void 0) { targetTexture = null; }
  71505. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71506. if (faceIndex === void 0) { faceIndex = 0; }
  71507. if (lodLevel === void 0) { lodLevel = 0; }
  71508. var engine = this._scene.getEngine();
  71509. for (var index = 0; index < postProcesses.length; index++) {
  71510. if (index < postProcesses.length - 1) {
  71511. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  71512. }
  71513. else {
  71514. if (targetTexture) {
  71515. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  71516. }
  71517. else {
  71518. engine.restoreDefaultFramebuffer();
  71519. }
  71520. }
  71521. var pp = postProcesses[index];
  71522. var effect = pp.apply();
  71523. if (effect) {
  71524. pp.onBeforeRenderObservable.notifyObservers(effect);
  71525. // VBOs
  71526. this._prepareBuffers();
  71527. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71528. // Draw order
  71529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71530. pp.onAfterRenderObservable.notifyObservers(effect);
  71531. }
  71532. }
  71533. // Restore depth buffer
  71534. engine.setDepthBuffer(true);
  71535. engine.setDepthWrite(true);
  71536. };
  71537. /**
  71538. * Finalize the result of the output of the postprocesses.
  71539. * @param doNotPresent If true the result will not be displayed to the screen.
  71540. * @param targetTexture The target texture to render to.
  71541. * @param faceIndex The index of the face to bind the target texture to.
  71542. * @param postProcesses The array of post processes to render.
  71543. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  71544. * @hidden
  71545. */
  71546. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  71547. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  71548. var camera = this._scene.activeCamera;
  71549. if (!camera) {
  71550. return;
  71551. }
  71552. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  71553. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  71554. return;
  71555. }
  71556. var engine = this._scene.getEngine();
  71557. for (var index = 0, len = postProcesses.length; index < len; index++) {
  71558. var pp = postProcesses[index];
  71559. if (index < len - 1) {
  71560. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  71561. }
  71562. else {
  71563. if (targetTexture) {
  71564. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  71565. pp._outputTexture = targetTexture;
  71566. }
  71567. else {
  71568. engine.restoreDefaultFramebuffer();
  71569. pp._outputTexture = null;
  71570. }
  71571. }
  71572. if (doNotPresent) {
  71573. break;
  71574. }
  71575. var effect = pp.apply();
  71576. if (effect) {
  71577. pp.onBeforeRenderObservable.notifyObservers(effect);
  71578. // VBOs
  71579. this._prepareBuffers();
  71580. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  71581. // Draw order
  71582. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71583. pp.onAfterRenderObservable.notifyObservers(effect);
  71584. }
  71585. }
  71586. // Restore states
  71587. engine.setDepthBuffer(true);
  71588. engine.setDepthWrite(true);
  71589. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71590. };
  71591. /**
  71592. * Disposes of the post process manager.
  71593. */
  71594. PostProcessManager.prototype.dispose = function () {
  71595. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71596. if (buffer) {
  71597. buffer.dispose();
  71598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71599. }
  71600. if (this._indexBuffer) {
  71601. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71602. this._indexBuffer = null;
  71603. }
  71604. };
  71605. return PostProcessManager;
  71606. }());
  71607. BABYLON.PostProcessManager = PostProcessManager;
  71608. })(BABYLON || (BABYLON = {}));
  71609. //# sourceMappingURL=babylon.postProcessManager.js.map
  71610. var BABYLON;
  71611. (function (BABYLON) {
  71612. /**
  71613. * PostProcess can be used to apply a shader to a texture after it has been rendered
  71614. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  71615. */
  71616. var PostProcess = /** @class */ (function () {
  71617. /**
  71618. * Creates a new instance PostProcess
  71619. * @param name The name of the PostProcess.
  71620. * @param fragmentUrl The url of the fragment shader to be used.
  71621. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  71622. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  71623. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  71624. * @param camera The camera to apply the render pass to.
  71625. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71626. * @param engine The engine which the post process will be applied. (default: current engine)
  71627. * @param reusable If the post process can be reused on the same frame. (default: false)
  71628. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  71629. * @param textureType Type of textures used when performing the post process. (default: 0)
  71630. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  71631. * @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
  71632. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  71633. */
  71634. function PostProcess(
  71635. /** Name of the PostProcess. */
  71636. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  71637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  71638. if (defines === void 0) { defines = null; }
  71639. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71640. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  71641. if (blockCompilation === void 0) { blockCompilation = false; }
  71642. this.name = name;
  71643. /**
  71644. * Width of the texture to apply the post process on
  71645. */
  71646. this.width = -1;
  71647. /**
  71648. * Height of the texture to apply the post process on
  71649. */
  71650. this.height = -1;
  71651. /**
  71652. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  71653. * @hidden
  71654. */
  71655. this._outputTexture = null;
  71656. /**
  71657. * If the buffer needs to be cleared before applying the post process. (default: true)
  71658. * Should be set to false if shader will overwrite all previous pixels.
  71659. */
  71660. this.autoClear = true;
  71661. /**
  71662. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  71663. */
  71664. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  71665. /**
  71666. * Animations to be used for the post processing
  71667. */
  71668. this.animations = new Array();
  71669. /**
  71670. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  71671. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  71672. */
  71673. this.enablePixelPerfectMode = false;
  71674. /**
  71675. * Force the postprocess to be applied without taking in account viewport
  71676. */
  71677. this.forceFullscreenViewport = true;
  71678. /**
  71679. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  71680. *
  71681. * | Value | Type | Description |
  71682. * | ----- | ----------------------------------- | ----------- |
  71683. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  71684. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  71685. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  71686. *
  71687. */
  71688. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  71689. /**
  71690. * Force textures to be a power of two (default: false)
  71691. */
  71692. this.alwaysForcePOT = false;
  71693. this._samples = 1;
  71694. /**
  71695. * Modify the scale of the post process to be the same as the viewport (default: false)
  71696. */
  71697. this.adaptScaleToCurrentViewport = false;
  71698. this._reusable = false;
  71699. /**
  71700. * Smart array of input and output textures for the post process.
  71701. * @hidden
  71702. */
  71703. this._textures = new BABYLON.SmartArray(2);
  71704. /**
  71705. * The index in _textures that corresponds to the output texture.
  71706. * @hidden
  71707. */
  71708. this._currentRenderTextureInd = 0;
  71709. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71710. this._texelSize = BABYLON.Vector2.Zero();
  71711. // Events
  71712. /**
  71713. * An event triggered when the postprocess is activated.
  71714. */
  71715. this.onActivateObservable = new BABYLON.Observable();
  71716. /**
  71717. * An event triggered when the postprocess changes its size.
  71718. */
  71719. this.onSizeChangedObservable = new BABYLON.Observable();
  71720. /**
  71721. * An event triggered when the postprocess applies its effect.
  71722. */
  71723. this.onApplyObservable = new BABYLON.Observable();
  71724. /**
  71725. * An event triggered before rendering the postprocess
  71726. */
  71727. this.onBeforeRenderObservable = new BABYLON.Observable();
  71728. /**
  71729. * An event triggered after rendering the postprocess
  71730. */
  71731. this.onAfterRenderObservable = new BABYLON.Observable();
  71732. if (camera != null) {
  71733. this._camera = camera;
  71734. this._scene = camera.getScene();
  71735. camera.attachPostProcess(this);
  71736. this._engine = this._scene.getEngine();
  71737. this._scene.postProcesses.push(this);
  71738. }
  71739. else if (engine) {
  71740. this._engine = engine;
  71741. this._engine.postProcesses.push(this);
  71742. }
  71743. this._options = options;
  71744. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71745. this._reusable = reusable || false;
  71746. this._textureType = textureType;
  71747. this._samplers = samplers || [];
  71748. this._samplers.push("textureSampler");
  71749. this._fragmentUrl = fragmentUrl;
  71750. this._vertexUrl = vertexUrl;
  71751. this._parameters = parameters || [];
  71752. this._parameters.push("scale");
  71753. this._indexParameters = indexParameters;
  71754. if (!blockCompilation) {
  71755. this.updateEffect(defines);
  71756. }
  71757. }
  71758. Object.defineProperty(PostProcess.prototype, "samples", {
  71759. /**
  71760. * Number of sample textures (default: 1)
  71761. */
  71762. get: function () {
  71763. return this._samples;
  71764. },
  71765. set: function (n) {
  71766. var _this = this;
  71767. this._samples = n;
  71768. this._textures.forEach(function (texture) {
  71769. if (texture.samples !== _this._samples) {
  71770. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71771. }
  71772. });
  71773. },
  71774. enumerable: true,
  71775. configurable: true
  71776. });
  71777. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71778. /**
  71779. * A function that is added to the onActivateObservable
  71780. */
  71781. set: function (callback) {
  71782. if (this._onActivateObserver) {
  71783. this.onActivateObservable.remove(this._onActivateObserver);
  71784. }
  71785. if (callback) {
  71786. this._onActivateObserver = this.onActivateObservable.add(callback);
  71787. }
  71788. },
  71789. enumerable: true,
  71790. configurable: true
  71791. });
  71792. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71793. /**
  71794. * A function that is added to the onSizeChangedObservable
  71795. */
  71796. set: function (callback) {
  71797. if (this._onSizeChangedObserver) {
  71798. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71799. }
  71800. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71801. },
  71802. enumerable: true,
  71803. configurable: true
  71804. });
  71805. Object.defineProperty(PostProcess.prototype, "onApply", {
  71806. /**
  71807. * A function that is added to the onApplyObservable
  71808. */
  71809. set: function (callback) {
  71810. if (this._onApplyObserver) {
  71811. this.onApplyObservable.remove(this._onApplyObserver);
  71812. }
  71813. this._onApplyObserver = this.onApplyObservable.add(callback);
  71814. },
  71815. enumerable: true,
  71816. configurable: true
  71817. });
  71818. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71819. /**
  71820. * A function that is added to the onBeforeRenderObservable
  71821. */
  71822. set: function (callback) {
  71823. if (this._onBeforeRenderObserver) {
  71824. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71825. }
  71826. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71827. },
  71828. enumerable: true,
  71829. configurable: true
  71830. });
  71831. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71832. /**
  71833. * A function that is added to the onAfterRenderObservable
  71834. */
  71835. set: function (callback) {
  71836. if (this._onAfterRenderObserver) {
  71837. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71838. }
  71839. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71840. },
  71841. enumerable: true,
  71842. configurable: true
  71843. });
  71844. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71845. /**
  71846. * 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
  71847. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71848. */
  71849. get: function () {
  71850. return this._textures.data[this._currentRenderTextureInd];
  71851. },
  71852. set: function (value) {
  71853. this._forcedOutputTexture = value;
  71854. },
  71855. enumerable: true,
  71856. configurable: true
  71857. });
  71858. /**
  71859. * Gets the camera which post process is applied to.
  71860. * @returns The camera the post process is applied to.
  71861. */
  71862. PostProcess.prototype.getCamera = function () {
  71863. return this._camera;
  71864. };
  71865. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71866. /**
  71867. * Gets the texel size of the postprocess.
  71868. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71869. */
  71870. get: function () {
  71871. if (this._shareOutputWithPostProcess) {
  71872. return this._shareOutputWithPostProcess.texelSize;
  71873. }
  71874. if (this._forcedOutputTexture) {
  71875. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71876. }
  71877. return this._texelSize;
  71878. },
  71879. enumerable: true,
  71880. configurable: true
  71881. });
  71882. /**
  71883. * Gets the engine which this post process belongs to.
  71884. * @returns The engine the post process was enabled with.
  71885. */
  71886. PostProcess.prototype.getEngine = function () {
  71887. return this._engine;
  71888. };
  71889. /**
  71890. * The effect that is created when initializing the post process.
  71891. * @returns The created effect corrisponding the the postprocess.
  71892. */
  71893. PostProcess.prototype.getEffect = function () {
  71894. return this._effect;
  71895. };
  71896. /**
  71897. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71898. * @param postProcess The post process to share the output with.
  71899. * @returns This post process.
  71900. */
  71901. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71902. this._disposeTextures();
  71903. this._shareOutputWithPostProcess = postProcess;
  71904. return this;
  71905. };
  71906. /**
  71907. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71908. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71909. */
  71910. PostProcess.prototype.useOwnOutput = function () {
  71911. if (this._textures.length == 0) {
  71912. this._textures = new BABYLON.SmartArray(2);
  71913. }
  71914. this._shareOutputWithPostProcess = null;
  71915. };
  71916. /**
  71917. * Updates the effect with the current post process compile time values and recompiles the shader.
  71918. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71919. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71920. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71921. * @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
  71922. * @param onCompiled Called when the shader has been compiled.
  71923. * @param onError Called if there is an error when compiling a shader.
  71924. */
  71925. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71926. if (defines === void 0) { defines = null; }
  71927. if (uniforms === void 0) { uniforms = null; }
  71928. if (samplers === void 0) { samplers = null; }
  71929. 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);
  71930. };
  71931. /**
  71932. * The post process is reusable if it can be used multiple times within one frame.
  71933. * @returns If the post process is reusable
  71934. */
  71935. PostProcess.prototype.isReusable = function () {
  71936. return this._reusable;
  71937. };
  71938. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71939. PostProcess.prototype.markTextureDirty = function () {
  71940. this.width = -1;
  71941. };
  71942. /**
  71943. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71944. * 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.
  71945. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71946. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71947. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71948. * @returns The target texture that was bound to be written to.
  71949. */
  71950. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71951. var _this = this;
  71952. if (sourceTexture === void 0) { sourceTexture = null; }
  71953. camera = camera || this._camera;
  71954. var scene = camera.getScene();
  71955. var engine = scene.getEngine();
  71956. var maxSize = engine.getCaps().maxTextureSize;
  71957. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71958. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71959. // 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
  71960. var webVRCamera = camera.parent;
  71961. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71962. requiredWidth /= 2;
  71963. }
  71964. var desiredWidth = (this._options.width || requiredWidth);
  71965. var desiredHeight = this._options.height || requiredHeight;
  71966. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71967. if (this.adaptScaleToCurrentViewport) {
  71968. var currentViewport = engine.currentViewport;
  71969. if (currentViewport) {
  71970. desiredWidth *= currentViewport.width;
  71971. desiredHeight *= currentViewport.height;
  71972. }
  71973. }
  71974. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71975. if (!this._options.width) {
  71976. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71977. }
  71978. if (!this._options.height) {
  71979. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71980. }
  71981. }
  71982. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71983. if (this._textures.length > 0) {
  71984. for (var i = 0; i < this._textures.length; i++) {
  71985. this._engine._releaseTexture(this._textures.data[i]);
  71986. }
  71987. this._textures.reset();
  71988. }
  71989. this.width = desiredWidth;
  71990. this.height = desiredHeight;
  71991. var textureSize = { width: this.width, height: this.height };
  71992. var textureOptions = {
  71993. generateMipMaps: false,
  71994. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71995. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71996. samplingMode: this.renderTargetSamplingMode,
  71997. type: this._textureType
  71998. };
  71999. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72000. if (this._reusable) {
  72001. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  72002. }
  72003. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  72004. this.onSizeChangedObservable.notifyObservers(this);
  72005. }
  72006. this._textures.forEach(function (texture) {
  72007. if (texture.samples !== _this.samples) {
  72008. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  72009. }
  72010. });
  72011. }
  72012. var target;
  72013. if (this._shareOutputWithPostProcess) {
  72014. target = this._shareOutputWithPostProcess.inputTexture;
  72015. }
  72016. else if (this._forcedOutputTexture) {
  72017. target = this._forcedOutputTexture;
  72018. this.width = this._forcedOutputTexture.width;
  72019. this.height = this._forcedOutputTexture.height;
  72020. }
  72021. else {
  72022. target = this.inputTexture;
  72023. }
  72024. // Bind the input of this post process to be used as the output of the previous post process.
  72025. if (this.enablePixelPerfectMode) {
  72026. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  72027. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  72028. }
  72029. else {
  72030. this._scaleRatio.copyFromFloats(1, 1);
  72031. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  72032. }
  72033. this.onActivateObservable.notifyObservers(camera);
  72034. // Clear
  72035. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  72036. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  72037. }
  72038. if (this._reusable) {
  72039. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  72040. }
  72041. return target;
  72042. };
  72043. Object.defineProperty(PostProcess.prototype, "isSupported", {
  72044. /**
  72045. * If the post process is supported.
  72046. */
  72047. get: function () {
  72048. return this._effect.isSupported;
  72049. },
  72050. enumerable: true,
  72051. configurable: true
  72052. });
  72053. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  72054. /**
  72055. * The aspect ratio of the output texture.
  72056. */
  72057. get: function () {
  72058. if (this._shareOutputWithPostProcess) {
  72059. return this._shareOutputWithPostProcess.aspectRatio;
  72060. }
  72061. if (this._forcedOutputTexture) {
  72062. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  72063. }
  72064. return this.width / this.height;
  72065. },
  72066. enumerable: true,
  72067. configurable: true
  72068. });
  72069. /**
  72070. * Get a value indicating if the post-process is ready to be used
  72071. * @returns true if the post-process is ready (shader is compiled)
  72072. */
  72073. PostProcess.prototype.isReady = function () {
  72074. return this._effect && this._effect.isReady();
  72075. };
  72076. /**
  72077. * Binds all textures and uniforms to the shader, this will be run on every pass.
  72078. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  72079. */
  72080. PostProcess.prototype.apply = function () {
  72081. // Check
  72082. if (!this._effect || !this._effect.isReady())
  72083. return null;
  72084. // States
  72085. this._engine.enableEffect(this._effect);
  72086. this._engine.setState(false);
  72087. this._engine.setDepthBuffer(false);
  72088. this._engine.setDepthWrite(false);
  72089. // Alpha
  72090. this._engine.setAlphaMode(this.alphaMode);
  72091. if (this.alphaConstants) {
  72092. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  72093. }
  72094. // Bind the output texture of the preivous post process as the input to this post process.
  72095. var source;
  72096. if (this._shareOutputWithPostProcess) {
  72097. source = this._shareOutputWithPostProcess.inputTexture;
  72098. }
  72099. else if (this._forcedOutputTexture) {
  72100. source = this._forcedOutputTexture;
  72101. }
  72102. else {
  72103. source = this.inputTexture;
  72104. }
  72105. this._effect._bindTexture("textureSampler", source);
  72106. // Parameters
  72107. this._effect.setVector2("scale", this._scaleRatio);
  72108. this.onApplyObservable.notifyObservers(this._effect);
  72109. return this._effect;
  72110. };
  72111. PostProcess.prototype._disposeTextures = function () {
  72112. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  72113. return;
  72114. }
  72115. if (this._textures.length > 0) {
  72116. for (var i = 0; i < this._textures.length; i++) {
  72117. this._engine._releaseTexture(this._textures.data[i]);
  72118. }
  72119. }
  72120. this._textures.dispose();
  72121. };
  72122. /**
  72123. * Disposes the post process.
  72124. * @param camera The camera to dispose the post process on.
  72125. */
  72126. PostProcess.prototype.dispose = function (camera) {
  72127. camera = camera || this._camera;
  72128. this._disposeTextures();
  72129. if (this._scene) {
  72130. var index_1 = this._scene.postProcesses.indexOf(this);
  72131. if (index_1 !== -1) {
  72132. this._scene.postProcesses.splice(index_1, 1);
  72133. }
  72134. }
  72135. else {
  72136. var index_2 = this._engine.postProcesses.indexOf(this);
  72137. if (index_2 !== -1) {
  72138. this._engine.postProcesses.splice(index_2, 1);
  72139. }
  72140. }
  72141. if (!camera) {
  72142. return;
  72143. }
  72144. camera.detachPostProcess(this);
  72145. var index = camera._postProcesses.indexOf(this);
  72146. if (index === 0 && camera._postProcesses.length > 0) {
  72147. var firstPostProcess = this._camera._getFirstPostProcess();
  72148. if (firstPostProcess) {
  72149. firstPostProcess.markTextureDirty();
  72150. }
  72151. }
  72152. this.onActivateObservable.clear();
  72153. this.onAfterRenderObservable.clear();
  72154. this.onApplyObservable.clear();
  72155. this.onBeforeRenderObservable.clear();
  72156. this.onSizeChangedObservable.clear();
  72157. };
  72158. return PostProcess;
  72159. }());
  72160. BABYLON.PostProcess = PostProcess;
  72161. })(BABYLON || (BABYLON = {}));
  72162. //# sourceMappingURL=babylon.postProcess.js.map
  72163. var BABYLON;
  72164. (function (BABYLON) {
  72165. var PassPostProcess = /** @class */ (function (_super) {
  72166. __extends(PassPostProcess, _super);
  72167. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72168. if (camera === void 0) { camera = null; }
  72169. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72170. if (blockCompilation === void 0) { blockCompilation = false; }
  72171. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  72172. }
  72173. return PassPostProcess;
  72174. }(BABYLON.PostProcess));
  72175. BABYLON.PassPostProcess = PassPostProcess;
  72176. })(BABYLON || (BABYLON = {}));
  72177. //# sourceMappingURL=babylon.passPostProcess.js.map
  72178. var __assign = (this && this.__assign) || function () {
  72179. __assign = Object.assign || function(t) {
  72180. for (var s, i = 1, n = arguments.length; i < n; i++) {
  72181. s = arguments[i];
  72182. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  72183. t[p] = s[p];
  72184. }
  72185. return t;
  72186. };
  72187. return __assign.apply(this, arguments);
  72188. };
  72189. var BABYLON;
  72190. (function (BABYLON) {
  72191. /**
  72192. * Default implementation IShadowGenerator.
  72193. * This is the main object responsible of generating shadows in the framework.
  72194. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  72195. */
  72196. var ShadowGenerator = /** @class */ (function () {
  72197. /**
  72198. * Creates a ShadowGenerator object.
  72199. * A ShadowGenerator is the required tool to use the shadows.
  72200. * Each light casting shadows needs to use its own ShadowGenerator.
  72201. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  72202. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  72203. * @param light The light object generating the shadows.
  72204. * @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.
  72205. */
  72206. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  72207. this._bias = 0.00005;
  72208. this._normalBias = 0;
  72209. this._blurBoxOffset = 1;
  72210. this._blurScale = 2;
  72211. this._blurKernel = 1;
  72212. this._useKernelBlur = false;
  72213. this._filter = ShadowGenerator.FILTER_NONE;
  72214. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  72215. this._contactHardeningLightSizeUVRatio = 0.1;
  72216. this._darkness = 0;
  72217. this._transparencyShadow = false;
  72218. /**
  72219. * Controls the extent to which the shadows fade out at the edge of the frustum
  72220. * Used only by directionals and spots
  72221. */
  72222. this.frustumEdgeFalloff = 0;
  72223. /**
  72224. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  72225. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  72226. * It might on the other hand introduce peter panning.
  72227. */
  72228. this.forceBackFacesOnly = false;
  72229. this._lightDirection = BABYLON.Vector3.Zero();
  72230. this._viewMatrix = BABYLON.Matrix.Zero();
  72231. this._projectionMatrix = BABYLON.Matrix.Zero();
  72232. this._transformMatrix = BABYLON.Matrix.Zero();
  72233. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72234. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  72235. this._currentFaceIndex = 0;
  72236. this._currentFaceIndexCache = 0;
  72237. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  72238. this._mapSize = mapSize;
  72239. this._light = light;
  72240. this._scene = light.getScene();
  72241. light._shadowGenerator = this;
  72242. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  72243. if (!component) {
  72244. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  72245. this._scene._addComponent(component);
  72246. }
  72247. // Texture type fallback from float to int if not supported.
  72248. var caps = this._scene.getEngine().getCaps();
  72249. if (!useFullFloatFirst) {
  72250. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72251. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72252. }
  72253. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72254. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72255. }
  72256. else {
  72257. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72258. }
  72259. }
  72260. else {
  72261. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  72262. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72263. }
  72264. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  72265. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72266. }
  72267. else {
  72268. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72269. }
  72270. }
  72271. this._initializeGenerator();
  72272. this._applyFilterValues();
  72273. }
  72274. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  72275. /**
  72276. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  72277. */
  72278. get: function () {
  72279. return this._bias;
  72280. },
  72281. /**
  72282. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  72283. */
  72284. set: function (bias) {
  72285. this._bias = bias;
  72286. },
  72287. enumerable: true,
  72288. configurable: true
  72289. });
  72290. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  72291. /**
  72292. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72293. */
  72294. get: function () {
  72295. return this._normalBias;
  72296. },
  72297. /**
  72298. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  72299. */
  72300. set: function (normalBias) {
  72301. this._normalBias = normalBias;
  72302. },
  72303. enumerable: true,
  72304. configurable: true
  72305. });
  72306. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  72307. /**
  72308. * Gets the blur box offset: offset applied during the blur pass.
  72309. * Only usefull if useKernelBlur = false
  72310. */
  72311. get: function () {
  72312. return this._blurBoxOffset;
  72313. },
  72314. /**
  72315. * Sets the blur box offset: offset applied during the blur pass.
  72316. * Only usefull if useKernelBlur = false
  72317. */
  72318. set: function (value) {
  72319. if (this._blurBoxOffset === value) {
  72320. return;
  72321. }
  72322. this._blurBoxOffset = value;
  72323. this._disposeBlurPostProcesses();
  72324. },
  72325. enumerable: true,
  72326. configurable: true
  72327. });
  72328. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  72329. /**
  72330. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  72331. * 2 means half of the size.
  72332. */
  72333. get: function () {
  72334. return this._blurScale;
  72335. },
  72336. /**
  72337. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  72338. * 2 means half of the size.
  72339. */
  72340. set: function (value) {
  72341. if (this._blurScale === value) {
  72342. return;
  72343. }
  72344. this._blurScale = value;
  72345. this._disposeBlurPostProcesses();
  72346. },
  72347. enumerable: true,
  72348. configurable: true
  72349. });
  72350. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  72351. /**
  72352. * Gets the blur kernel: kernel size of the blur pass.
  72353. * Only usefull if useKernelBlur = true
  72354. */
  72355. get: function () {
  72356. return this._blurKernel;
  72357. },
  72358. /**
  72359. * Sets the blur kernel: kernel size of the blur pass.
  72360. * Only usefull if useKernelBlur = true
  72361. */
  72362. set: function (value) {
  72363. if (this._blurKernel === value) {
  72364. return;
  72365. }
  72366. this._blurKernel = value;
  72367. this._disposeBlurPostProcesses();
  72368. },
  72369. enumerable: true,
  72370. configurable: true
  72371. });
  72372. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  72373. /**
  72374. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  72375. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72376. */
  72377. get: function () {
  72378. return this._useKernelBlur;
  72379. },
  72380. /**
  72381. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  72382. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  72383. */
  72384. set: function (value) {
  72385. if (this._useKernelBlur === value) {
  72386. return;
  72387. }
  72388. this._useKernelBlur = value;
  72389. this._disposeBlurPostProcesses();
  72390. },
  72391. enumerable: true,
  72392. configurable: true
  72393. });
  72394. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  72395. /**
  72396. * Gets the depth scale used in ESM mode.
  72397. */
  72398. get: function () {
  72399. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  72400. },
  72401. /**
  72402. * Sets the depth scale used in ESM mode.
  72403. * This can override the scale stored on the light.
  72404. */
  72405. set: function (value) {
  72406. this._depthScale = value;
  72407. },
  72408. enumerable: true,
  72409. configurable: true
  72410. });
  72411. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  72412. /**
  72413. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  72414. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72415. */
  72416. get: function () {
  72417. return this._filter;
  72418. },
  72419. /**
  72420. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  72421. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  72422. */
  72423. set: function (value) {
  72424. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  72425. if (this._light.needCube()) {
  72426. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72427. this.useExponentialShadowMap = true;
  72428. return;
  72429. }
  72430. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72431. this.useCloseExponentialShadowMap = true;
  72432. return;
  72433. }
  72434. // PCF on cubemap would also be expensive
  72435. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72436. this.usePoissonSampling = true;
  72437. return;
  72438. }
  72439. }
  72440. // Weblg1 fallback for PCF.
  72441. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  72442. if (this._scene.getEngine().webGLVersion === 1) {
  72443. this.usePoissonSampling = true;
  72444. return;
  72445. }
  72446. }
  72447. if (this._filter === value) {
  72448. return;
  72449. }
  72450. this._filter = value;
  72451. this._disposeBlurPostProcesses();
  72452. this._applyFilterValues();
  72453. this._light._markMeshesAsLightDirty();
  72454. },
  72455. enumerable: true,
  72456. configurable: true
  72457. });
  72458. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  72459. /**
  72460. * Gets if the current filter is set to Poisson Sampling.
  72461. */
  72462. get: function () {
  72463. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  72464. },
  72465. /**
  72466. * Sets the current filter to Poisson Sampling.
  72467. */
  72468. set: function (value) {
  72469. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  72470. return;
  72471. }
  72472. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  72473. },
  72474. enumerable: true,
  72475. configurable: true
  72476. });
  72477. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  72478. /**
  72479. * Gets if the current filter is set to VSM.
  72480. * DEPRECATED. Should use useExponentialShadowMap instead.
  72481. */
  72482. get: function () {
  72483. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72484. return this.useExponentialShadowMap;
  72485. },
  72486. /**
  72487. * Sets the current filter is to VSM.
  72488. * DEPRECATED. Should use useExponentialShadowMap instead.
  72489. */
  72490. set: function (value) {
  72491. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  72492. this.useExponentialShadowMap = value;
  72493. },
  72494. enumerable: true,
  72495. configurable: true
  72496. });
  72497. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  72498. /**
  72499. * Gets if the current filter is set to blurred VSM.
  72500. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72501. */
  72502. get: function () {
  72503. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72504. return this.useBlurExponentialShadowMap;
  72505. },
  72506. /**
  72507. * Sets the current filter is to blurred VSM.
  72508. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  72509. */
  72510. set: function (value) {
  72511. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  72512. this.useBlurExponentialShadowMap = value;
  72513. },
  72514. enumerable: true,
  72515. configurable: true
  72516. });
  72517. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  72518. /**
  72519. * Gets if the current filter is set to ESM.
  72520. */
  72521. get: function () {
  72522. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  72523. },
  72524. /**
  72525. * Sets the current filter is to ESM.
  72526. */
  72527. set: function (value) {
  72528. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  72529. return;
  72530. }
  72531. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72532. },
  72533. enumerable: true,
  72534. configurable: true
  72535. });
  72536. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  72537. /**
  72538. * Gets if the current filter is set to filtered ESM.
  72539. */
  72540. get: function () {
  72541. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  72542. },
  72543. /**
  72544. * Gets if the current filter is set to filtered ESM.
  72545. */
  72546. set: function (value) {
  72547. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  72548. return;
  72549. }
  72550. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72551. },
  72552. enumerable: true,
  72553. configurable: true
  72554. });
  72555. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  72556. /**
  72557. * Gets if the current filter is set to "close ESM" (using the inverse of the
  72558. * exponential to prevent steep falloff artifacts).
  72559. */
  72560. get: function () {
  72561. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  72562. },
  72563. /**
  72564. * Sets the current filter to "close ESM" (using the inverse of the
  72565. * exponential to prevent steep falloff artifacts).
  72566. */
  72567. set: function (value) {
  72568. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  72569. return;
  72570. }
  72571. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72572. },
  72573. enumerable: true,
  72574. configurable: true
  72575. });
  72576. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  72577. /**
  72578. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  72579. * exponential to prevent steep falloff artifacts).
  72580. */
  72581. get: function () {
  72582. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  72583. },
  72584. /**
  72585. * Sets the current filter to filtered "close ESM" (using the inverse of the
  72586. * exponential to prevent steep falloff artifacts).
  72587. */
  72588. set: function (value) {
  72589. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  72590. return;
  72591. }
  72592. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  72593. },
  72594. enumerable: true,
  72595. configurable: true
  72596. });
  72597. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  72598. /**
  72599. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  72600. */
  72601. get: function () {
  72602. return this.filter === ShadowGenerator.FILTER_PCF;
  72603. },
  72604. /**
  72605. * Sets the current filter to "PCF" (percentage closer filtering).
  72606. */
  72607. set: function (value) {
  72608. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  72609. return;
  72610. }
  72611. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  72612. },
  72613. enumerable: true,
  72614. configurable: true
  72615. });
  72616. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  72617. /**
  72618. * Gets the PCF or PCSS Quality.
  72619. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72620. */
  72621. get: function () {
  72622. return this._filteringQuality;
  72623. },
  72624. /**
  72625. * Sets the PCF or PCSS Quality.
  72626. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  72627. */
  72628. set: function (filteringQuality) {
  72629. this._filteringQuality = filteringQuality;
  72630. },
  72631. enumerable: true,
  72632. configurable: true
  72633. });
  72634. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  72635. /**
  72636. * Gets if the current filter is set to "PCSS" (contact hardening).
  72637. */
  72638. get: function () {
  72639. return this.filter === ShadowGenerator.FILTER_PCSS;
  72640. },
  72641. /**
  72642. * Sets the current filter to "PCSS" (contact hardening).
  72643. */
  72644. set: function (value) {
  72645. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  72646. return;
  72647. }
  72648. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  72649. },
  72650. enumerable: true,
  72651. configurable: true
  72652. });
  72653. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  72654. /**
  72655. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72656. * Using a ratio helps keeping shape stability independently of the map size.
  72657. *
  72658. * It does not account for the light projection as it was having too much
  72659. * instability during the light setup or during light position changes.
  72660. *
  72661. * Only valid if useContactHardeningShadow is true.
  72662. */
  72663. get: function () {
  72664. return this._contactHardeningLightSizeUVRatio;
  72665. },
  72666. /**
  72667. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  72668. * Using a ratio helps keeping shape stability independently of the map size.
  72669. *
  72670. * It does not account for the light projection as it was having too much
  72671. * instability during the light setup or during light position changes.
  72672. *
  72673. * Only valid if useContactHardeningShadow is true.
  72674. */
  72675. set: function (contactHardeningLightSizeUVRatio) {
  72676. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  72677. },
  72678. enumerable: true,
  72679. configurable: true
  72680. });
  72681. /**
  72682. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  72683. * 0 means strongest and 1 would means no shadow.
  72684. * @returns the darkness.
  72685. */
  72686. ShadowGenerator.prototype.getDarkness = function () {
  72687. return this._darkness;
  72688. };
  72689. /**
  72690. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  72691. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  72692. * @returns the shadow generator allowing fluent coding.
  72693. */
  72694. ShadowGenerator.prototype.setDarkness = function (darkness) {
  72695. if (darkness >= 1.0)
  72696. this._darkness = 1.0;
  72697. else if (darkness <= 0.0)
  72698. this._darkness = 0.0;
  72699. else
  72700. this._darkness = darkness;
  72701. return this;
  72702. };
  72703. /**
  72704. * Sets the ability to have transparent shadow (boolean).
  72705. * @param transparent True if transparent else False
  72706. * @returns the shadow generator allowing fluent coding
  72707. */
  72708. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72709. this._transparencyShadow = transparent;
  72710. return this;
  72711. };
  72712. /**
  72713. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72714. * @returns The render target texture if present otherwise, null
  72715. */
  72716. ShadowGenerator.prototype.getShadowMap = function () {
  72717. return this._shadowMap;
  72718. };
  72719. /**
  72720. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72721. * @returns The render target texture if the shadow map is present otherwise, null
  72722. */
  72723. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72724. if (this._shadowMap2) {
  72725. return this._shadowMap2;
  72726. }
  72727. return this._shadowMap;
  72728. };
  72729. /**
  72730. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72731. * @param mesh Mesh to add
  72732. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72733. * @returns the Shadow Generator itself
  72734. */
  72735. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72736. if (includeDescendants === void 0) { includeDescendants = true; }
  72737. var _a;
  72738. if (!this._shadowMap) {
  72739. return this;
  72740. }
  72741. if (!this._shadowMap.renderList) {
  72742. this._shadowMap.renderList = [];
  72743. }
  72744. this._shadowMap.renderList.push(mesh);
  72745. if (includeDescendants) {
  72746. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72747. }
  72748. return this;
  72749. };
  72750. /**
  72751. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72752. * @param mesh Mesh to remove
  72753. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72754. * @returns the Shadow Generator itself
  72755. */
  72756. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72757. if (includeDescendants === void 0) { includeDescendants = true; }
  72758. if (!this._shadowMap || !this._shadowMap.renderList) {
  72759. return this;
  72760. }
  72761. var index = this._shadowMap.renderList.indexOf(mesh);
  72762. if (index !== -1) {
  72763. this._shadowMap.renderList.splice(index, 1);
  72764. }
  72765. if (includeDescendants) {
  72766. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72767. var child = _a[_i];
  72768. this.removeShadowCaster(child);
  72769. }
  72770. }
  72771. return this;
  72772. };
  72773. /**
  72774. * Returns the associated light object.
  72775. * @returns the light generating the shadow
  72776. */
  72777. ShadowGenerator.prototype.getLight = function () {
  72778. return this._light;
  72779. };
  72780. ShadowGenerator.prototype._initializeGenerator = function () {
  72781. this._light._markMeshesAsLightDirty();
  72782. this._initializeShadowMap();
  72783. };
  72784. ShadowGenerator.prototype._initializeShadowMap = function () {
  72785. var _this = this;
  72786. // Render target
  72787. var engine = this._scene.getEngine();
  72788. if (engine.webGLVersion > 1) {
  72789. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72790. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72791. }
  72792. else {
  72793. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72794. }
  72795. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72796. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72797. this._shadowMap.anisotropicFilteringLevel = 1;
  72798. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72799. this._shadowMap.renderParticles = false;
  72800. this._shadowMap.ignoreCameraViewport = true;
  72801. // Record Face Index before render.
  72802. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72803. _this._currentFaceIndex = faceIndex;
  72804. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72805. engine.setColorWrite(false);
  72806. }
  72807. });
  72808. // Custom render function.
  72809. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72810. // Blur if required afer render.
  72811. this._shadowMap.onAfterUnbindObservable.add(function () {
  72812. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72813. engine.setColorWrite(true);
  72814. }
  72815. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72816. return;
  72817. }
  72818. var shadowMap = _this.getShadowMapForRendering();
  72819. if (shadowMap) {
  72820. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72821. }
  72822. });
  72823. // Clear according to the chosen filter.
  72824. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72825. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72826. this._shadowMap.onClearObservable.add(function (engine) {
  72827. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72828. engine.clear(clearOne, false, true, false);
  72829. }
  72830. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72831. engine.clear(clearZero, true, true, false);
  72832. }
  72833. else {
  72834. engine.clear(clearOne, true, true, false);
  72835. }
  72836. });
  72837. };
  72838. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72839. var _this = this;
  72840. var engine = this._scene.getEngine();
  72841. var targetSize = this._mapSize / this.blurScale;
  72842. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72843. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72844. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72845. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72846. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72847. }
  72848. if (this.useKernelBlur) {
  72849. 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);
  72850. this._kernelBlurXPostprocess.width = targetSize;
  72851. this._kernelBlurXPostprocess.height = targetSize;
  72852. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72853. effect.setTexture("textureSampler", _this._shadowMap);
  72854. });
  72855. 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);
  72856. this._kernelBlurXPostprocess.autoClear = false;
  72857. this._kernelBlurYPostprocess.autoClear = false;
  72858. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72859. this._kernelBlurXPostprocess.packedFloat = true;
  72860. this._kernelBlurYPostprocess.packedFloat = true;
  72861. }
  72862. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72863. }
  72864. else {
  72865. 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);
  72866. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72867. effect.setFloat2("screenSize", targetSize, targetSize);
  72868. effect.setTexture("textureSampler", _this._shadowMap);
  72869. });
  72870. this._boxBlurPostprocess.autoClear = false;
  72871. this._blurPostProcesses = [this._boxBlurPostprocess];
  72872. }
  72873. };
  72874. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72875. var index;
  72876. var engine = this._scene.getEngine();
  72877. if (depthOnlySubMeshes.length) {
  72878. engine.setColorWrite(false);
  72879. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72880. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72881. }
  72882. engine.setColorWrite(true);
  72883. }
  72884. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72885. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72886. }
  72887. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72888. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72889. }
  72890. if (this._transparencyShadow) {
  72891. for (index = 0; index < transparentSubMeshes.length; index++) {
  72892. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72893. }
  72894. }
  72895. };
  72896. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72897. var _this = this;
  72898. var mesh = subMesh.getRenderingMesh();
  72899. var scene = this._scene;
  72900. var engine = scene.getEngine();
  72901. var material = subMesh.getMaterial();
  72902. if (!material) {
  72903. return;
  72904. }
  72905. // Culling
  72906. engine.setState(material.backFaceCulling);
  72907. // Managing instances
  72908. var batch = mesh._getInstancesRenderList(subMesh._id);
  72909. if (batch.mustReturn) {
  72910. return;
  72911. }
  72912. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72913. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72914. engine.enableEffect(this._effect);
  72915. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72916. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72917. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72918. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72919. this._effect.setVector3("lightData", this._cachedDirection);
  72920. }
  72921. else {
  72922. this._effect.setVector3("lightData", this._cachedPosition);
  72923. }
  72924. if (scene.activeCamera) {
  72925. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72926. }
  72927. // Alpha test
  72928. if (material && material.needAlphaTesting()) {
  72929. var alphaTexture = material.getAlphaTestTexture();
  72930. if (alphaTexture) {
  72931. this._effect.setTexture("diffuseSampler", alphaTexture);
  72932. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72933. }
  72934. }
  72935. // Bones
  72936. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72937. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72938. }
  72939. // Morph targets
  72940. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72941. if (this.forceBackFacesOnly) {
  72942. engine.setState(true, 0, false, true);
  72943. }
  72944. // Draw
  72945. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72946. if (this.forceBackFacesOnly) {
  72947. engine.setState(true, 0, false, false);
  72948. }
  72949. }
  72950. else {
  72951. // Need to reset refresh rate of the shadowMap
  72952. if (this._shadowMap) {
  72953. this._shadowMap.resetRefreshCounter();
  72954. }
  72955. }
  72956. };
  72957. ShadowGenerator.prototype._applyFilterValues = function () {
  72958. if (!this._shadowMap) {
  72959. return;
  72960. }
  72961. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72962. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72963. }
  72964. else {
  72965. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72966. }
  72967. };
  72968. /**
  72969. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72970. * @param onCompiled Callback triggered at the and of the effects compilation
  72971. * @param options Sets of optional options forcing the compilation with different modes
  72972. */
  72973. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72974. var _this = this;
  72975. var localOptions = __assign({ useInstances: false }, options);
  72976. var shadowMap = this.getShadowMap();
  72977. if (!shadowMap) {
  72978. if (onCompiled) {
  72979. onCompiled(this);
  72980. }
  72981. return;
  72982. }
  72983. var renderList = shadowMap.renderList;
  72984. if (!renderList) {
  72985. if (onCompiled) {
  72986. onCompiled(this);
  72987. }
  72988. return;
  72989. }
  72990. var subMeshes = new Array();
  72991. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72992. var mesh = renderList_1[_i];
  72993. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72994. }
  72995. if (subMeshes.length === 0) {
  72996. if (onCompiled) {
  72997. onCompiled(this);
  72998. }
  72999. return;
  73000. }
  73001. var currentIndex = 0;
  73002. var checkReady = function () {
  73003. if (!_this._scene || !_this._scene.getEngine()) {
  73004. return;
  73005. }
  73006. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  73007. currentIndex++;
  73008. if (currentIndex >= subMeshes.length) {
  73009. if (onCompiled) {
  73010. onCompiled(_this);
  73011. }
  73012. return;
  73013. }
  73014. }
  73015. setTimeout(checkReady, 16);
  73016. };
  73017. checkReady();
  73018. };
  73019. /**
  73020. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  73021. * @param options Sets of optional options forcing the compilation with different modes
  73022. * @returns A promise that resolves when the compilation completes
  73023. */
  73024. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  73025. var _this = this;
  73026. return new Promise(function (resolve) {
  73027. _this.forceCompilation(function () {
  73028. resolve();
  73029. }, options);
  73030. });
  73031. };
  73032. /**
  73033. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  73034. * @param subMesh The submesh we want to render in the shadow map
  73035. * @param useInstances Defines wether will draw in the map using instances
  73036. * @returns true if ready otherwise, false
  73037. */
  73038. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  73039. var defines = [];
  73040. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73041. defines.push("#define FLOAT");
  73042. }
  73043. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73044. defines.push("#define ESM");
  73045. }
  73046. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  73047. defines.push("#define DEPTHTEXTURE");
  73048. }
  73049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73050. var mesh = subMesh.getMesh();
  73051. var material = subMesh.getMaterial();
  73052. // Normal bias.
  73053. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73054. attribs.push(BABYLON.VertexBuffer.NormalKind);
  73055. defines.push("#define NORMAL");
  73056. if (mesh.nonUniformScaling) {
  73057. defines.push("#define NONUNIFORMSCALING");
  73058. }
  73059. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  73060. defines.push("#define DIRECTIONINLIGHTDATA");
  73061. }
  73062. }
  73063. // Alpha test
  73064. if (material && material.needAlphaTesting()) {
  73065. var alphaTexture = material.getAlphaTestTexture();
  73066. if (alphaTexture) {
  73067. defines.push("#define ALPHATEST");
  73068. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73069. attribs.push(BABYLON.VertexBuffer.UVKind);
  73070. defines.push("#define UV1");
  73071. }
  73072. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73073. if (alphaTexture.coordinatesIndex === 1) {
  73074. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73075. defines.push("#define UV2");
  73076. }
  73077. }
  73078. }
  73079. }
  73080. // Bones
  73081. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73082. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73083. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73084. if (mesh.numBoneInfluencers > 4) {
  73085. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73086. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73087. }
  73088. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73089. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  73090. }
  73091. else {
  73092. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73093. }
  73094. // Morph targets
  73095. var manager = mesh.morphTargetManager;
  73096. var morphInfluencers = 0;
  73097. if (manager) {
  73098. if (manager.numInfluencers > 0) {
  73099. defines.push("#define MORPHTARGETS");
  73100. morphInfluencers = manager.numInfluencers;
  73101. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  73102. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  73103. }
  73104. }
  73105. // Instances
  73106. if (useInstances) {
  73107. defines.push("#define INSTANCES");
  73108. attribs.push("world0");
  73109. attribs.push("world1");
  73110. attribs.push("world2");
  73111. attribs.push("world3");
  73112. }
  73113. // Get correct effect
  73114. var join = defines.join("\n");
  73115. if (this._cachedDefines !== join) {
  73116. this._cachedDefines = join;
  73117. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  73118. }
  73119. if (!this._effect.isReady()) {
  73120. return false;
  73121. }
  73122. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73123. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  73124. this._initializeBlurRTTAndPostProcesses();
  73125. }
  73126. }
  73127. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  73128. return false;
  73129. }
  73130. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  73131. return false;
  73132. }
  73133. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  73134. return false;
  73135. }
  73136. return true;
  73137. };
  73138. /**
  73139. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  73140. * @param defines Defines of the material we want to update
  73141. * @param lightIndex Index of the light in the enabled light list of the material
  73142. */
  73143. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  73144. var scene = this._scene;
  73145. var light = this._light;
  73146. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73147. return;
  73148. }
  73149. defines["SHADOW" + lightIndex] = true;
  73150. if (this.useContactHardeningShadow) {
  73151. defines["SHADOWPCSS" + lightIndex] = true;
  73152. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73153. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73154. }
  73155. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73156. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73157. }
  73158. // else default to high.
  73159. }
  73160. if (this.usePercentageCloserFiltering) {
  73161. defines["SHADOWPCF" + lightIndex] = true;
  73162. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  73163. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  73164. }
  73165. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  73166. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  73167. }
  73168. // else default to high.
  73169. }
  73170. else if (this.usePoissonSampling) {
  73171. defines["SHADOWPOISSON" + lightIndex] = true;
  73172. }
  73173. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  73174. defines["SHADOWESM" + lightIndex] = true;
  73175. }
  73176. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  73177. defines["SHADOWCLOSEESM" + lightIndex] = true;
  73178. }
  73179. if (light.needCube()) {
  73180. defines["SHADOWCUBE" + lightIndex] = true;
  73181. }
  73182. };
  73183. /**
  73184. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  73185. * defined in the generator but impacting the effect).
  73186. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  73187. * @param effect The effect we are binfing the information for
  73188. */
  73189. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  73190. var light = this._light;
  73191. var scene = this._scene;
  73192. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  73193. return;
  73194. }
  73195. var camera = scene.activeCamera;
  73196. if (!camera) {
  73197. return;
  73198. }
  73199. var shadowMap = this.getShadowMap();
  73200. if (!shadowMap) {
  73201. return;
  73202. }
  73203. if (!light.needCube()) {
  73204. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  73205. }
  73206. // Only PCF uses depth stencil texture.
  73207. if (this._filter === ShadowGenerator.FILTER_PCF) {
  73208. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73209. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73210. }
  73211. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  73212. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73213. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  73214. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  73215. }
  73216. else {
  73217. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  73218. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  73219. }
  73220. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  73221. };
  73222. /**
  73223. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  73224. * (eq to shadow prjection matrix * light transform matrix)
  73225. * @returns The transform matrix used to create the shadow map
  73226. */
  73227. ShadowGenerator.prototype.getTransformMatrix = function () {
  73228. var scene = this._scene;
  73229. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  73230. return this._transformMatrix;
  73231. }
  73232. this._currentRenderID = scene.getRenderId();
  73233. this._currentFaceIndexCache = this._currentFaceIndex;
  73234. var lightPosition = this._light.position;
  73235. if (this._light.computeTransformedInformation()) {
  73236. lightPosition = this._light.transformedPosition;
  73237. }
  73238. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  73239. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  73240. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  73241. }
  73242. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  73243. this._cachedPosition.copyFrom(lightPosition);
  73244. this._cachedDirection.copyFrom(this._lightDirection);
  73245. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  73246. var shadowMap = this.getShadowMap();
  73247. if (shadowMap) {
  73248. var renderList = shadowMap.renderList;
  73249. if (renderList) {
  73250. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  73251. }
  73252. }
  73253. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  73254. }
  73255. return this._transformMatrix;
  73256. };
  73257. /**
  73258. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  73259. * Cube and 2D textures for instance.
  73260. */
  73261. ShadowGenerator.prototype.recreateShadowMap = function () {
  73262. var shadowMap = this._shadowMap;
  73263. if (!shadowMap) {
  73264. return;
  73265. }
  73266. // Track render list.
  73267. var renderList = shadowMap.renderList;
  73268. // Clean up existing data.
  73269. this._disposeRTTandPostProcesses();
  73270. // Reinitializes.
  73271. this._initializeGenerator();
  73272. // Reaffect the filter to ensure a correct fallback if necessary.
  73273. this.filter = this.filter;
  73274. // Reaffect the filter.
  73275. this._applyFilterValues();
  73276. // Reaffect Render List.
  73277. this._shadowMap.renderList = renderList;
  73278. };
  73279. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  73280. if (this._shadowMap2) {
  73281. this._shadowMap2.dispose();
  73282. this._shadowMap2 = null;
  73283. }
  73284. if (this._boxBlurPostprocess) {
  73285. this._boxBlurPostprocess.dispose();
  73286. this._boxBlurPostprocess = null;
  73287. }
  73288. if (this._kernelBlurXPostprocess) {
  73289. this._kernelBlurXPostprocess.dispose();
  73290. this._kernelBlurXPostprocess = null;
  73291. }
  73292. if (this._kernelBlurYPostprocess) {
  73293. this._kernelBlurYPostprocess.dispose();
  73294. this._kernelBlurYPostprocess = null;
  73295. }
  73296. this._blurPostProcesses = [];
  73297. };
  73298. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  73299. if (this._shadowMap) {
  73300. this._shadowMap.dispose();
  73301. this._shadowMap = null;
  73302. }
  73303. this._disposeBlurPostProcesses();
  73304. };
  73305. /**
  73306. * Disposes the ShadowGenerator.
  73307. * Returns nothing.
  73308. */
  73309. ShadowGenerator.prototype.dispose = function () {
  73310. this._disposeRTTandPostProcesses();
  73311. if (this._light) {
  73312. this._light._shadowGenerator = null;
  73313. this._light._markMeshesAsLightDirty();
  73314. }
  73315. };
  73316. /**
  73317. * Serializes the shadow generator setup to a json object.
  73318. * @returns The serialized JSON object
  73319. */
  73320. ShadowGenerator.prototype.serialize = function () {
  73321. var serializationObject = {};
  73322. var shadowMap = this.getShadowMap();
  73323. if (!shadowMap) {
  73324. return serializationObject;
  73325. }
  73326. serializationObject.lightId = this._light.id;
  73327. serializationObject.mapSize = shadowMap.getRenderSize();
  73328. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  73329. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  73330. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73331. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  73332. serializationObject.usePoissonSampling = this.usePoissonSampling;
  73333. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  73334. serializationObject.depthScale = this.depthScale;
  73335. serializationObject.darkness = this.getDarkness();
  73336. serializationObject.blurBoxOffset = this.blurBoxOffset;
  73337. serializationObject.blurKernel = this.blurKernel;
  73338. serializationObject.blurScale = this.blurScale;
  73339. serializationObject.useKernelBlur = this.useKernelBlur;
  73340. serializationObject.transparencyShadow = this._transparencyShadow;
  73341. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  73342. serializationObject.bias = this.bias;
  73343. serializationObject.normalBias = this.normalBias;
  73344. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  73345. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  73346. serializationObject.filteringQuality = this.filteringQuality;
  73347. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  73348. serializationObject.renderList = [];
  73349. if (shadowMap.renderList) {
  73350. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  73351. var mesh = shadowMap.renderList[meshIndex];
  73352. serializationObject.renderList.push(mesh.id);
  73353. }
  73354. }
  73355. return serializationObject;
  73356. };
  73357. /**
  73358. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  73359. * @param parsedShadowGenerator The JSON object to parse
  73360. * @param scene The scene to create the shadow map for
  73361. * @returns The parsed shadow generator
  73362. */
  73363. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  73364. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  73365. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  73366. var shadowMap = shadowGenerator.getShadowMap();
  73367. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  73368. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  73369. meshes.forEach(function (mesh) {
  73370. if (!shadowMap) {
  73371. return;
  73372. }
  73373. if (!shadowMap.renderList) {
  73374. shadowMap.renderList = [];
  73375. }
  73376. shadowMap.renderList.push(mesh);
  73377. });
  73378. }
  73379. if (parsedShadowGenerator.usePoissonSampling) {
  73380. shadowGenerator.usePoissonSampling = true;
  73381. }
  73382. else if (parsedShadowGenerator.useExponentialShadowMap) {
  73383. shadowGenerator.useExponentialShadowMap = true;
  73384. }
  73385. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  73386. shadowGenerator.useBlurExponentialShadowMap = true;
  73387. }
  73388. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  73389. shadowGenerator.useCloseExponentialShadowMap = true;
  73390. }
  73391. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  73392. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  73393. }
  73394. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  73395. shadowGenerator.usePercentageCloserFiltering = true;
  73396. }
  73397. else if (parsedShadowGenerator.useContactHardeningShadow) {
  73398. shadowGenerator.useContactHardeningShadow = true;
  73399. }
  73400. if (parsedShadowGenerator.filteringQuality) {
  73401. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  73402. }
  73403. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  73404. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  73405. }
  73406. // Backward compat
  73407. else if (parsedShadowGenerator.useVarianceShadowMap) {
  73408. shadowGenerator.useExponentialShadowMap = true;
  73409. }
  73410. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  73411. shadowGenerator.useBlurExponentialShadowMap = true;
  73412. }
  73413. if (parsedShadowGenerator.depthScale) {
  73414. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  73415. }
  73416. if (parsedShadowGenerator.blurScale) {
  73417. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  73418. }
  73419. if (parsedShadowGenerator.blurBoxOffset) {
  73420. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  73421. }
  73422. if (parsedShadowGenerator.useKernelBlur) {
  73423. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  73424. }
  73425. if (parsedShadowGenerator.blurKernel) {
  73426. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  73427. }
  73428. if (parsedShadowGenerator.bias !== undefined) {
  73429. shadowGenerator.bias = parsedShadowGenerator.bias;
  73430. }
  73431. if (parsedShadowGenerator.normalBias !== undefined) {
  73432. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  73433. }
  73434. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  73435. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  73436. }
  73437. if (parsedShadowGenerator.darkness) {
  73438. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  73439. }
  73440. if (parsedShadowGenerator.transparencyShadow) {
  73441. shadowGenerator.setTransparencyShadow(true);
  73442. }
  73443. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  73444. return shadowGenerator;
  73445. };
  73446. /**
  73447. * Shadow generator mode None: no filtering applied.
  73448. */
  73449. ShadowGenerator.FILTER_NONE = 0;
  73450. /**
  73451. * Shadow generator mode ESM: Exponential Shadow Mapping.
  73452. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73453. */
  73454. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  73455. /**
  73456. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  73457. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  73458. */
  73459. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  73460. /**
  73461. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  73462. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73463. */
  73464. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  73465. /**
  73466. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  73467. * edge artifacts on steep falloff.
  73468. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73469. */
  73470. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  73471. /**
  73472. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  73473. * edge artifacts on steep falloff.
  73474. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  73475. */
  73476. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  73477. /**
  73478. * Shadow generator mode PCF: Percentage Closer Filtering
  73479. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73480. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  73481. */
  73482. ShadowGenerator.FILTER_PCF = 6;
  73483. /**
  73484. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  73485. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  73486. * Contact Hardening
  73487. */
  73488. ShadowGenerator.FILTER_PCSS = 7;
  73489. /**
  73490. * Reserved for PCF and PCSS
  73491. * Highest Quality.
  73492. *
  73493. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  73494. *
  73495. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  73496. */
  73497. ShadowGenerator.QUALITY_HIGH = 0;
  73498. /**
  73499. * Reserved for PCF and PCSS
  73500. * Good tradeoff for quality/perf cross devices
  73501. *
  73502. * Execute PCF on a 3*3 kernel.
  73503. *
  73504. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  73505. */
  73506. ShadowGenerator.QUALITY_MEDIUM = 1;
  73507. /**
  73508. * Reserved for PCF and PCSS
  73509. * The lowest quality but the fastest.
  73510. *
  73511. * Execute PCF on a 1*1 kernel.
  73512. *
  73513. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  73514. */
  73515. ShadowGenerator.QUALITY_LOW = 2;
  73516. return ShadowGenerator;
  73517. }());
  73518. BABYLON.ShadowGenerator = ShadowGenerator;
  73519. })(BABYLON || (BABYLON = {}));
  73520. //# sourceMappingURL=babylon.shadowGenerator.js.map
  73521. var BABYLON;
  73522. (function (BABYLON) {
  73523. // Adds the parser to the scene parsers.
  73524. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  73525. // Shadows
  73526. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  73527. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  73528. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  73529. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  73530. // SG would be available on their associated lights
  73531. }
  73532. }
  73533. });
  73534. /**
  73535. * Defines the shadow generator component responsible to manage any shadow generators
  73536. * in a given scene.
  73537. */
  73538. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  73539. /**
  73540. * Creates a new instance of the component for the given scene
  73541. * @param scene Defines the scene to register the component in
  73542. */
  73543. function ShadowGeneratorSceneComponent(scene) {
  73544. /**
  73545. * The component name helpfull to identify the component in the list of scene components.
  73546. */
  73547. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  73548. this.scene = scene;
  73549. }
  73550. /**
  73551. * Registers the component in a given scene
  73552. */
  73553. ShadowGeneratorSceneComponent.prototype.register = function () {
  73554. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  73555. };
  73556. /**
  73557. * Rebuilds the elements related to this component in case of
  73558. * context lost for instance.
  73559. */
  73560. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  73561. // Nothing To Do Here.
  73562. };
  73563. /**
  73564. * Serializes the component data to the specified json object
  73565. * @param serializationObject The object to serialize to
  73566. */
  73567. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  73568. // Shadows
  73569. serializationObject.shadowGenerators = [];
  73570. var lights = this.scene.lights;
  73571. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  73572. var light = lights_1[_i];
  73573. var shadowGenerator = light.getShadowGenerator();
  73574. if (shadowGenerator) {
  73575. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73576. }
  73577. }
  73578. };
  73579. /**
  73580. * Adds all the element from the container to the scene
  73581. * @param container the container holding the elements
  73582. */
  73583. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  73584. // Nothing To Do Here. (directly attached to a light)
  73585. };
  73586. /**
  73587. * Removes all the elements in the container from the scene
  73588. * @param container contains the elements to remove
  73589. */
  73590. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  73591. // Nothing To Do Here. (directly attached to a light)
  73592. };
  73593. /**
  73594. * Rebuilds the elements related to this component in case of
  73595. * context lost for instance.
  73596. */
  73597. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  73598. // Nothing To Do Here.
  73599. };
  73600. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  73601. // Shadows
  73602. var scene = this.scene;
  73603. if (this.scene.shadowsEnabled) {
  73604. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  73605. var light = scene.lights[lightIndex];
  73606. var shadowGenerator = light.getShadowGenerator();
  73607. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  73608. var shadowMap = (shadowGenerator.getShadowMap());
  73609. if (scene.textures.indexOf(shadowMap) !== -1) {
  73610. renderTargets.push(shadowMap);
  73611. }
  73612. }
  73613. }
  73614. }
  73615. };
  73616. return ShadowGeneratorSceneComponent;
  73617. }());
  73618. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  73619. })(BABYLON || (BABYLON = {}));
  73620. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  73621. var BABYLON;
  73622. (function (BABYLON) {
  73623. var DefaultLoadingScreen = /** @class */ (function () {
  73624. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  73625. if (_loadingText === void 0) { _loadingText = ""; }
  73626. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  73627. var _this = this;
  73628. this._renderingCanvas = _renderingCanvas;
  73629. this._loadingText = _loadingText;
  73630. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  73631. // Resize
  73632. this._resizeLoadingUI = function () {
  73633. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  73634. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  73635. if (!_this._loadingDiv) {
  73636. return;
  73637. }
  73638. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  73639. _this._loadingDiv.style.left = canvasRect.left + "px";
  73640. _this._loadingDiv.style.top = canvasRect.top + "px";
  73641. _this._loadingDiv.style.width = canvasRect.width + "px";
  73642. _this._loadingDiv.style.height = canvasRect.height + "px";
  73643. };
  73644. }
  73645. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  73646. if (this._loadingDiv) {
  73647. // Do not add a loading screen if there is already one
  73648. return;
  73649. }
  73650. this._loadingDiv = document.createElement("div");
  73651. this._loadingDiv.id = "babylonjsLoadingDiv";
  73652. this._loadingDiv.style.opacity = "0";
  73653. this._loadingDiv.style.transition = "opacity 1.5s ease";
  73654. this._loadingDiv.style.pointerEvents = "none";
  73655. // Loading text
  73656. this._loadingTextDiv = document.createElement("div");
  73657. this._loadingTextDiv.style.position = "absolute";
  73658. this._loadingTextDiv.style.left = "0";
  73659. this._loadingTextDiv.style.top = "50%";
  73660. this._loadingTextDiv.style.marginTop = "80px";
  73661. this._loadingTextDiv.style.width = "100%";
  73662. this._loadingTextDiv.style.height = "20px";
  73663. this._loadingTextDiv.style.fontFamily = "Arial";
  73664. this._loadingTextDiv.style.fontSize = "14px";
  73665. this._loadingTextDiv.style.color = "white";
  73666. this._loadingTextDiv.style.textAlign = "center";
  73667. this._loadingTextDiv.innerHTML = "Loading";
  73668. this._loadingDiv.appendChild(this._loadingTextDiv);
  73669. //set the predefined text
  73670. this._loadingTextDiv.innerHTML = this._loadingText;
  73671. // Generating keyframes
  73672. var style = document.createElement('style');
  73673. style.type = 'text/css';
  73674. 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 }";
  73675. style.innerHTML = keyFrames;
  73676. document.getElementsByTagName('head')[0].appendChild(style);
  73677. // Loading img
  73678. var imgBack = new Image();
  73679. 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";
  73680. imgBack.style.position = "absolute";
  73681. imgBack.style.left = "50%";
  73682. imgBack.style.top = "50%";
  73683. imgBack.style.marginLeft = "-60px";
  73684. imgBack.style.marginTop = "-60px";
  73685. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  73686. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  73687. imgBack.style.transformOrigin = "50% 50%";
  73688. imgBack.style.webkitTransformOrigin = "50% 50%";
  73689. this._loadingDiv.appendChild(imgBack);
  73690. this._resizeLoadingUI();
  73691. window.addEventListener("resize", this._resizeLoadingUI);
  73692. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73693. document.body.appendChild(this._loadingDiv);
  73694. this._loadingDiv.style.opacity = "1";
  73695. };
  73696. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  73697. var _this = this;
  73698. if (!this._loadingDiv) {
  73699. return;
  73700. }
  73701. var onTransitionEnd = function () {
  73702. if (!_this._loadingDiv) {
  73703. return;
  73704. }
  73705. document.body.removeChild(_this._loadingDiv);
  73706. window.removeEventListener("resize", _this._resizeLoadingUI);
  73707. _this._loadingDiv = null;
  73708. };
  73709. this._loadingDiv.style.opacity = "0";
  73710. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73711. };
  73712. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73713. set: function (text) {
  73714. this._loadingText = text;
  73715. if (this._loadingTextDiv) {
  73716. this._loadingTextDiv.innerHTML = this._loadingText;
  73717. }
  73718. },
  73719. enumerable: true,
  73720. configurable: true
  73721. });
  73722. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73723. get: function () {
  73724. return this._loadingDivBackgroundColor;
  73725. },
  73726. set: function (color) {
  73727. this._loadingDivBackgroundColor = color;
  73728. if (!this._loadingDiv) {
  73729. return;
  73730. }
  73731. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73732. },
  73733. enumerable: true,
  73734. configurable: true
  73735. });
  73736. return DefaultLoadingScreen;
  73737. }());
  73738. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73739. })(BABYLON || (BABYLON = {}));
  73740. //# sourceMappingURL=babylon.loadingScreen.js.map
  73741. var BABYLON;
  73742. (function (BABYLON) {
  73743. var SceneLoaderProgressEvent = /** @class */ (function () {
  73744. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73745. this.lengthComputable = lengthComputable;
  73746. this.loaded = loaded;
  73747. this.total = total;
  73748. }
  73749. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73750. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73751. };
  73752. return SceneLoaderProgressEvent;
  73753. }());
  73754. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73755. var SceneLoader = /** @class */ (function () {
  73756. function SceneLoader() {
  73757. }
  73758. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73759. get: function () {
  73760. return 0;
  73761. },
  73762. enumerable: true,
  73763. configurable: true
  73764. });
  73765. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73766. get: function () {
  73767. return 1;
  73768. },
  73769. enumerable: true,
  73770. configurable: true
  73771. });
  73772. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73773. get: function () {
  73774. return 2;
  73775. },
  73776. enumerable: true,
  73777. configurable: true
  73778. });
  73779. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73780. get: function () {
  73781. return 3;
  73782. },
  73783. enumerable: true,
  73784. configurable: true
  73785. });
  73786. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73787. get: function () {
  73788. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73789. },
  73790. set: function (value) {
  73791. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73792. },
  73793. enumerable: true,
  73794. configurable: true
  73795. });
  73796. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73797. get: function () {
  73798. return SceneLoader._ShowLoadingScreen;
  73799. },
  73800. set: function (value) {
  73801. SceneLoader._ShowLoadingScreen = value;
  73802. },
  73803. enumerable: true,
  73804. configurable: true
  73805. });
  73806. Object.defineProperty(SceneLoader, "loggingLevel", {
  73807. get: function () {
  73808. return SceneLoader._loggingLevel;
  73809. },
  73810. set: function (value) {
  73811. SceneLoader._loggingLevel = value;
  73812. },
  73813. enumerable: true,
  73814. configurable: true
  73815. });
  73816. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73817. get: function () {
  73818. return SceneLoader._CleanBoneMatrixWeights;
  73819. },
  73820. set: function (value) {
  73821. SceneLoader._CleanBoneMatrixWeights = value;
  73822. },
  73823. enumerable: true,
  73824. configurable: true
  73825. });
  73826. SceneLoader._getDefaultPlugin = function () {
  73827. return SceneLoader._registeredPlugins[".babylon"];
  73828. };
  73829. SceneLoader._getPluginForExtension = function (extension) {
  73830. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73831. if (registeredPlugin) {
  73832. return registeredPlugin;
  73833. }
  73834. 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");
  73835. return SceneLoader._getDefaultPlugin();
  73836. };
  73837. SceneLoader._getPluginForDirectLoad = function (data) {
  73838. for (var extension in SceneLoader._registeredPlugins) {
  73839. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73840. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73841. return SceneLoader._registeredPlugins[extension];
  73842. }
  73843. }
  73844. return SceneLoader._getDefaultPlugin();
  73845. };
  73846. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73847. var queryStringPosition = sceneFilename.indexOf("?");
  73848. if (queryStringPosition !== -1) {
  73849. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73850. }
  73851. var dotPosition = sceneFilename.lastIndexOf(".");
  73852. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73853. return SceneLoader._getPluginForExtension(extension);
  73854. };
  73855. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73856. SceneLoader._getDirectLoad = function (sceneFilename) {
  73857. if (sceneFilename.substr(0, 5) === "data:") {
  73858. return sceneFilename.substr(5);
  73859. }
  73860. return null;
  73861. };
  73862. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73863. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73864. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73865. var plugin;
  73866. if (registeredPlugin.plugin.createPlugin) {
  73867. plugin = registeredPlugin.plugin.createPlugin();
  73868. }
  73869. else {
  73870. plugin = registeredPlugin.plugin;
  73871. }
  73872. var useArrayBuffer = registeredPlugin.isBinary;
  73873. var database;
  73874. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73875. var dataCallback = function (data, responseURL) {
  73876. if (scene.isDisposed) {
  73877. onError("Scene has been disposed");
  73878. return;
  73879. }
  73880. scene.database = database;
  73881. onSuccess(plugin, data, responseURL);
  73882. };
  73883. var request = null;
  73884. var pluginDisposed = false;
  73885. var onDisposeObservable = plugin.onDisposeObservable;
  73886. if (onDisposeObservable) {
  73887. onDisposeObservable.add(function () {
  73888. pluginDisposed = true;
  73889. if (request) {
  73890. request.abort();
  73891. request = null;
  73892. }
  73893. onDispose();
  73894. });
  73895. }
  73896. var manifestChecked = function () {
  73897. if (pluginDisposed) {
  73898. return;
  73899. }
  73900. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73901. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73902. } : undefined, database, useArrayBuffer, function (request, exception) {
  73903. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  73904. });
  73905. };
  73906. if (directLoad) {
  73907. dataCallback(directLoad);
  73908. return plugin;
  73909. }
  73910. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73911. var engine = scene.getEngine();
  73912. var canUseOfflineSupport = engine.enableOfflineSupport;
  73913. if (canUseOfflineSupport) {
  73914. // Also check for exceptions
  73915. var exceptionFound = false;
  73916. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73917. var regex = _a[_i];
  73918. if (regex.test(fileInfo.url)) {
  73919. exceptionFound = true;
  73920. break;
  73921. }
  73922. }
  73923. canUseOfflineSupport = !exceptionFound;
  73924. }
  73925. if (canUseOfflineSupport) {
  73926. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73927. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73928. }
  73929. else {
  73930. manifestChecked();
  73931. }
  73932. }
  73933. // Loading file from disk via input file or drag'n'drop
  73934. else {
  73935. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73936. if (file) {
  73937. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73938. }
  73939. else {
  73940. onError("Unable to find file named " + fileInfo.name);
  73941. }
  73942. }
  73943. return plugin;
  73944. };
  73945. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73946. var url;
  73947. var name;
  73948. if (!sceneFilename) {
  73949. url = rootUrl;
  73950. name = BABYLON.Tools.GetFilename(rootUrl);
  73951. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73952. }
  73953. else {
  73954. if (sceneFilename.substr(0, 1) === "/") {
  73955. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73956. return null;
  73957. }
  73958. url = rootUrl + sceneFilename;
  73959. name = sceneFilename;
  73960. }
  73961. ;
  73962. return {
  73963. url: url,
  73964. rootUrl: rootUrl,
  73965. name: name
  73966. };
  73967. };
  73968. // Public functions
  73969. SceneLoader.GetPluginForExtension = function (extension) {
  73970. return SceneLoader._getPluginForExtension(extension).plugin;
  73971. };
  73972. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73973. return !!SceneLoader._registeredPlugins[extension];
  73974. };
  73975. SceneLoader.RegisterPlugin = function (plugin) {
  73976. if (typeof plugin.extensions === "string") {
  73977. var extension = plugin.extensions;
  73978. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73979. plugin: plugin,
  73980. isBinary: false
  73981. };
  73982. }
  73983. else {
  73984. var extensions = plugin.extensions;
  73985. Object.keys(extensions).forEach(function (extension) {
  73986. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73987. plugin: plugin,
  73988. isBinary: extensions[extension].isBinary
  73989. };
  73990. });
  73991. }
  73992. };
  73993. /**
  73994. * Import meshes into a scene
  73995. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73996. * @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)
  73997. * @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)
  73998. * @param scene the instance of BABYLON.Scene to append to
  73999. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  74000. * @param onProgress a callback with a progress event for each file being loaded
  74001. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74002. * @param pluginExtension the extension used to determine the plugin
  74003. * @returns The loaded plugin
  74004. */
  74005. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74006. if (sceneFilename === void 0) { sceneFilename = ""; }
  74007. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74008. if (onSuccess === void 0) { onSuccess = null; }
  74009. if (onProgress === void 0) { onProgress = null; }
  74010. if (onError === void 0) { onError = null; }
  74011. if (pluginExtension === void 0) { pluginExtension = null; }
  74012. if (!scene) {
  74013. BABYLON.Tools.Error("No scene available to import mesh to");
  74014. return null;
  74015. }
  74016. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74017. if (!fileInfo) {
  74018. return null;
  74019. }
  74020. var loadingToken = {};
  74021. scene._addPendingData(loadingToken);
  74022. var disposeHandler = function () {
  74023. scene._removePendingData(loadingToken);
  74024. };
  74025. var errorHandler = function (message, exception) {
  74026. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  74027. if (onError) {
  74028. onError(scene, errorMessage, exception);
  74029. }
  74030. else {
  74031. BABYLON.Tools.Error(errorMessage);
  74032. // should the exception be thrown?
  74033. }
  74034. disposeHandler();
  74035. };
  74036. var progressHandler = onProgress ? function (event) {
  74037. try {
  74038. onProgress(event);
  74039. }
  74040. catch (e) {
  74041. errorHandler("Error in onProgress callback", e);
  74042. }
  74043. } : undefined;
  74044. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  74045. scene.importedMeshesFiles.push(fileInfo.url);
  74046. if (onSuccess) {
  74047. try {
  74048. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  74049. }
  74050. catch (e) {
  74051. errorHandler("Error in onSuccess callback", e);
  74052. }
  74053. }
  74054. scene._removePendingData(loadingToken);
  74055. };
  74056. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74057. if (plugin.rewriteRootURL) {
  74058. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  74059. }
  74060. if (plugin.importMesh) {
  74061. var syncedPlugin = plugin;
  74062. var meshes = new Array();
  74063. var particleSystems = new Array();
  74064. var skeletons = new Array();
  74065. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  74066. return;
  74067. }
  74068. scene.loadingPluginName = plugin.name;
  74069. successHandler(meshes, particleSystems, skeletons, []);
  74070. }
  74071. else {
  74072. var asyncedPlugin = plugin;
  74073. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  74074. scene.loadingPluginName = plugin.name;
  74075. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  74076. }).catch(function (error) {
  74077. errorHandler(error.message, error);
  74078. });
  74079. }
  74080. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74081. };
  74082. /**
  74083. * Import meshes into a scene
  74084. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  74085. * @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)
  74086. * @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)
  74087. * @param scene the instance of BABYLON.Scene to append to
  74088. * @param onProgress a callback with a progress event for each file being loaded
  74089. * @param pluginExtension the extension used to determine the plugin
  74090. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  74091. */
  74092. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74093. if (sceneFilename === void 0) { sceneFilename = ""; }
  74094. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74095. if (onProgress === void 0) { onProgress = null; }
  74096. if (pluginExtension === void 0) { pluginExtension = null; }
  74097. return new Promise(function (resolve, reject) {
  74098. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  74099. resolve({
  74100. meshes: meshes,
  74101. particleSystems: particleSystems,
  74102. skeletons: skeletons,
  74103. animationGroups: animationGroups
  74104. });
  74105. }, onProgress, function (scene, message, exception) {
  74106. reject(exception || new Error(message));
  74107. }, pluginExtension);
  74108. });
  74109. };
  74110. /**
  74111. * Load a scene
  74112. * @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)
  74113. * @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)
  74114. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74115. * @param onSuccess a callback with the scene when import succeeds
  74116. * @param onProgress a callback with a progress event for each file being loaded
  74117. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74118. * @param pluginExtension the extension used to determine the plugin
  74119. * @returns The loaded plugin
  74120. */
  74121. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  74122. if (onSuccess === void 0) { onSuccess = null; }
  74123. if (onProgress === void 0) { onProgress = null; }
  74124. if (onError === void 0) { onError = null; }
  74125. if (pluginExtension === void 0) { pluginExtension = null; }
  74126. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  74127. };
  74128. /**
  74129. * Load a scene
  74130. * @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)
  74131. * @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)
  74132. * @param engine is the instance of BABYLON.Engine to use to create the scene
  74133. * @param onProgress a callback with a progress event for each file being loaded
  74134. * @param pluginExtension the extension used to determine the plugin
  74135. * @returns The loaded scene
  74136. */
  74137. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  74138. if (onProgress === void 0) { onProgress = null; }
  74139. if (pluginExtension === void 0) { pluginExtension = null; }
  74140. return new Promise(function (resolve, reject) {
  74141. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  74142. resolve(scene);
  74143. }, onProgress, function (scene, message, exception) {
  74144. reject(exception || new Error(message));
  74145. }, pluginExtension);
  74146. });
  74147. };
  74148. /**
  74149. * Append a scene
  74150. * @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)
  74151. * @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)
  74152. * @param scene is the instance of BABYLON.Scene to append to
  74153. * @param onSuccess a callback with the scene when import succeeds
  74154. * @param onProgress a callback with a progress event for each file being loaded
  74155. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74156. * @param pluginExtension the extension used to determine the plugin
  74157. * @returns The loaded plugin
  74158. */
  74159. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74160. if (sceneFilename === void 0) { sceneFilename = ""; }
  74161. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74162. if (onSuccess === void 0) { onSuccess = null; }
  74163. if (onProgress === void 0) { onProgress = null; }
  74164. if (onError === void 0) { onError = null; }
  74165. if (pluginExtension === void 0) { pluginExtension = null; }
  74166. if (!scene) {
  74167. BABYLON.Tools.Error("No scene available to append to");
  74168. return null;
  74169. }
  74170. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74171. if (!fileInfo) {
  74172. return null;
  74173. }
  74174. if (SceneLoader.ShowLoadingScreen) {
  74175. scene.getEngine().displayLoadingUI();
  74176. }
  74177. var loadingToken = {};
  74178. scene._addPendingData(loadingToken);
  74179. var disposeHandler = function () {
  74180. scene._removePendingData(loadingToken);
  74181. scene.getEngine().hideLoadingUI();
  74182. };
  74183. var errorHandler = function (message, exception) {
  74184. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  74185. if (onError) {
  74186. onError(scene, errorMessage, exception);
  74187. }
  74188. else {
  74189. BABYLON.Tools.Error(errorMessage);
  74190. // should the exception be thrown?
  74191. }
  74192. disposeHandler();
  74193. };
  74194. var progressHandler = onProgress ? function (event) {
  74195. try {
  74196. onProgress(event);
  74197. }
  74198. catch (e) {
  74199. errorHandler("Error in onProgress callback", e);
  74200. }
  74201. } : undefined;
  74202. var successHandler = function () {
  74203. if (onSuccess) {
  74204. try {
  74205. onSuccess(scene);
  74206. }
  74207. catch (e) {
  74208. errorHandler("Error in onSuccess callback", e);
  74209. }
  74210. }
  74211. scene._removePendingData(loadingToken);
  74212. };
  74213. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74214. if (plugin.load) {
  74215. var syncedPlugin = plugin;
  74216. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  74217. return;
  74218. }
  74219. scene.loadingPluginName = plugin.name;
  74220. successHandler();
  74221. }
  74222. else {
  74223. var asyncedPlugin = plugin;
  74224. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  74225. scene.loadingPluginName = plugin.name;
  74226. successHandler();
  74227. }).catch(function (error) {
  74228. errorHandler(error.message, error);
  74229. });
  74230. }
  74231. if (SceneLoader.ShowLoadingScreen) {
  74232. scene.executeWhenReady(function () {
  74233. scene.getEngine().hideLoadingUI();
  74234. });
  74235. }
  74236. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74237. };
  74238. /**
  74239. * Append a scene
  74240. * @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)
  74241. * @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)
  74242. * @param scene is the instance of BABYLON.Scene to append to
  74243. * @param onProgress a callback with a progress event for each file being loaded
  74244. * @param pluginExtension the extension used to determine the plugin
  74245. * @returns The given scene
  74246. */
  74247. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74248. if (sceneFilename === void 0) { sceneFilename = ""; }
  74249. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74250. if (onProgress === void 0) { onProgress = null; }
  74251. if (pluginExtension === void 0) { pluginExtension = null; }
  74252. return new Promise(function (resolve, reject) {
  74253. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  74254. resolve(scene);
  74255. }, onProgress, function (scene, message, exception) {
  74256. reject(exception || new Error(message));
  74257. }, pluginExtension);
  74258. });
  74259. };
  74260. /**
  74261. * Load a scene into an asset container
  74262. * @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)
  74263. * @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)
  74264. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  74265. * @param onSuccess a callback with the scene when import succeeds
  74266. * @param onProgress a callback with a progress event for each file being loaded
  74267. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  74268. * @param pluginExtension the extension used to determine the plugin
  74269. * @returns The loaded plugin
  74270. */
  74271. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  74272. if (sceneFilename === void 0) { sceneFilename = ""; }
  74273. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74274. if (onSuccess === void 0) { onSuccess = null; }
  74275. if (onProgress === void 0) { onProgress = null; }
  74276. if (onError === void 0) { onError = null; }
  74277. if (pluginExtension === void 0) { pluginExtension = null; }
  74278. if (!scene) {
  74279. BABYLON.Tools.Error("No scene available to load asset container to");
  74280. return null;
  74281. }
  74282. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  74283. if (!fileInfo) {
  74284. return null;
  74285. }
  74286. var loadingToken = {};
  74287. scene._addPendingData(loadingToken);
  74288. var disposeHandler = function () {
  74289. scene._removePendingData(loadingToken);
  74290. };
  74291. var errorHandler = function (message, exception) {
  74292. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  74293. if (onError) {
  74294. onError(scene, errorMessage, exception);
  74295. }
  74296. else {
  74297. BABYLON.Tools.Error(errorMessage);
  74298. // should the exception be thrown?
  74299. }
  74300. disposeHandler();
  74301. };
  74302. var progressHandler = onProgress ? function (event) {
  74303. try {
  74304. onProgress(event);
  74305. }
  74306. catch (e) {
  74307. errorHandler("Error in onProgress callback", e);
  74308. }
  74309. } : undefined;
  74310. var successHandler = function (assets) {
  74311. if (onSuccess) {
  74312. try {
  74313. onSuccess(assets);
  74314. }
  74315. catch (e) {
  74316. errorHandler("Error in onSuccess callback", e);
  74317. }
  74318. }
  74319. scene._removePendingData(loadingToken);
  74320. };
  74321. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  74322. if (plugin.loadAssetContainer) {
  74323. var syncedPlugin = plugin;
  74324. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  74325. if (!assetContainer) {
  74326. return;
  74327. }
  74328. scene.loadingPluginName = plugin.name;
  74329. successHandler(assetContainer);
  74330. }
  74331. else if (plugin.loadAssetContainerAsync) {
  74332. var asyncedPlugin = plugin;
  74333. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  74334. scene.loadingPluginName = plugin.name;
  74335. successHandler(assetContainer);
  74336. }).catch(function (error) {
  74337. errorHandler(error.message, error);
  74338. });
  74339. }
  74340. else {
  74341. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  74342. }
  74343. if (SceneLoader.ShowLoadingScreen) {
  74344. scene.executeWhenReady(function () {
  74345. scene.getEngine().hideLoadingUI();
  74346. });
  74347. }
  74348. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  74349. };
  74350. /**
  74351. * Load a scene into an asset container
  74352. * @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)
  74353. * @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)
  74354. * @param scene is the instance of BABYLON.Scene to append to
  74355. * @param onProgress a callback with a progress event for each file being loaded
  74356. * @param pluginExtension the extension used to determine the plugin
  74357. * @returns The loaded asset container
  74358. */
  74359. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  74360. if (sceneFilename === void 0) { sceneFilename = ""; }
  74361. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  74362. if (onProgress === void 0) { onProgress = null; }
  74363. if (pluginExtension === void 0) { pluginExtension = null; }
  74364. return new Promise(function (resolve, reject) {
  74365. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  74366. resolve(assetContainer);
  74367. }, onProgress, function (scene, message, exception) {
  74368. reject(exception || new Error(message));
  74369. }, pluginExtension);
  74370. });
  74371. };
  74372. // Flags
  74373. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  74374. SceneLoader._ShowLoadingScreen = true;
  74375. SceneLoader._CleanBoneMatrixWeights = false;
  74376. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  74377. // Members
  74378. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  74379. SceneLoader._registeredPlugins = {};
  74380. return SceneLoader;
  74381. }());
  74382. BABYLON.SceneLoader = SceneLoader;
  74383. ;
  74384. })(BABYLON || (BABYLON = {}));
  74385. //# sourceMappingURL=babylon.sceneLoader.js.map
  74386. var BABYLON;
  74387. (function (BABYLON) {
  74388. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  74389. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74390. var parsedMaterial = parsedData.materials[index];
  74391. if (parsedMaterial.id === id) {
  74392. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74393. }
  74394. }
  74395. return null;
  74396. };
  74397. var isDescendantOf = function (mesh, names, hierarchyIds) {
  74398. for (var i in names) {
  74399. if (mesh.name === names[i]) {
  74400. hierarchyIds.push(mesh.id);
  74401. return true;
  74402. }
  74403. }
  74404. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  74405. hierarchyIds.push(mesh.id);
  74406. return true;
  74407. }
  74408. return false;
  74409. };
  74410. var logOperation = function (operation, producer) {
  74411. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  74412. };
  74413. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  74414. if (addToScene === void 0) { addToScene = false; }
  74415. var container = new BABYLON.AssetContainer(scene);
  74416. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74417. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74418. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74419. // and avoid problems with multiple concurrent .babylon loads.
  74420. var log = "importScene has failed JSON parse";
  74421. try {
  74422. var parsedData = JSON.parse(data);
  74423. log = "";
  74424. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74425. var index;
  74426. var cache;
  74427. // Lights
  74428. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  74429. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  74430. var parsedLight = parsedData.lights[index];
  74431. var light = BABYLON.Light.Parse(parsedLight, scene);
  74432. if (light) {
  74433. container.lights.push(light);
  74434. log += (index === 0 ? "\n\tLights:" : "");
  74435. log += "\n\t\t" + light.toString(fullDetails);
  74436. }
  74437. }
  74438. }
  74439. // Animations
  74440. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  74441. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  74442. var parsedAnimation = parsedData.animations[index];
  74443. var animation = BABYLON.Animation.Parse(parsedAnimation);
  74444. scene.animations.push(animation);
  74445. container.animations.push(animation);
  74446. log += (index === 0 ? "\n\tAnimations:" : "");
  74447. log += "\n\t\t" + animation.toString(fullDetails);
  74448. }
  74449. }
  74450. // Materials
  74451. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  74452. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  74453. var parsedMaterial = parsedData.materials[index];
  74454. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  74455. container.materials.push(mat);
  74456. log += (index === 0 ? "\n\tMaterials:" : "");
  74457. log += "\n\t\t" + mat.toString(fullDetails);
  74458. }
  74459. }
  74460. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74461. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  74462. var parsedMultiMaterial = parsedData.multiMaterials[index];
  74463. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74464. container.multiMaterials.push(mmat);
  74465. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  74466. log += "\n\t\t" + mmat.toString(fullDetails);
  74467. }
  74468. }
  74469. // Morph targets
  74470. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74471. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74472. var managerData = _a[_i];
  74473. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  74474. }
  74475. }
  74476. // Skeletons
  74477. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74478. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  74479. var parsedSkeleton = parsedData.skeletons[index];
  74480. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74481. container.skeletons.push(skeleton);
  74482. log += (index === 0 ? "\n\tSkeletons:" : "");
  74483. log += "\n\t\t" + skeleton.toString(fullDetails);
  74484. }
  74485. }
  74486. // Geometries
  74487. var geometries = parsedData.geometries;
  74488. if (geometries !== undefined && geometries !== null) {
  74489. var addedGeometry = new Array();
  74490. // Boxes
  74491. var boxes = geometries.boxes;
  74492. if (boxes !== undefined && boxes !== null) {
  74493. for (index = 0, cache = boxes.length; index < cache; index++) {
  74494. var parsedBox = boxes[index];
  74495. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  74496. }
  74497. }
  74498. // Spheres
  74499. var spheres = geometries.spheres;
  74500. if (spheres !== undefined && spheres !== null) {
  74501. for (index = 0, cache = spheres.length; index < cache; index++) {
  74502. var parsedSphere = spheres[index];
  74503. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  74504. }
  74505. }
  74506. // Cylinders
  74507. var cylinders = geometries.cylinders;
  74508. if (cylinders !== undefined && cylinders !== null) {
  74509. for (index = 0, cache = cylinders.length; index < cache; index++) {
  74510. var parsedCylinder = cylinders[index];
  74511. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  74512. }
  74513. }
  74514. // Toruses
  74515. var toruses = geometries.toruses;
  74516. if (toruses !== undefined && toruses !== null) {
  74517. for (index = 0, cache = toruses.length; index < cache; index++) {
  74518. var parsedTorus = toruses[index];
  74519. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  74520. }
  74521. }
  74522. // Grounds
  74523. var grounds = geometries.grounds;
  74524. if (grounds !== undefined && grounds !== null) {
  74525. for (index = 0, cache = grounds.length; index < cache; index++) {
  74526. var parsedGround = grounds[index];
  74527. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  74528. }
  74529. }
  74530. // Planes
  74531. var planes = geometries.planes;
  74532. if (planes !== undefined && planes !== null) {
  74533. for (index = 0, cache = planes.length; index < cache; index++) {
  74534. var parsedPlane = planes[index];
  74535. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  74536. }
  74537. }
  74538. // TorusKnots
  74539. var torusKnots = geometries.torusKnots;
  74540. if (torusKnots !== undefined && torusKnots !== null) {
  74541. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  74542. var parsedTorusKnot = torusKnots[index];
  74543. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  74544. }
  74545. }
  74546. // VertexData
  74547. var vertexData = geometries.vertexData;
  74548. if (vertexData !== undefined && vertexData !== null) {
  74549. for (index = 0, cache = vertexData.length; index < cache; index++) {
  74550. var parsedVertexData = vertexData[index];
  74551. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  74552. }
  74553. }
  74554. addedGeometry.forEach(function (g) {
  74555. if (g) {
  74556. container.geometries.push(g);
  74557. }
  74558. });
  74559. }
  74560. // Transform nodes
  74561. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  74562. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  74563. var parsedTransformNode = parsedData.transformNodes[index];
  74564. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  74565. container.transformNodes.push(node);
  74566. }
  74567. }
  74568. // Meshes
  74569. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74570. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74571. var parsedMesh = parsedData.meshes[index];
  74572. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74573. container.meshes.push(mesh);
  74574. log += (index === 0 ? "\n\tMeshes:" : "");
  74575. log += "\n\t\t" + mesh.toString(fullDetails);
  74576. }
  74577. }
  74578. // Cameras
  74579. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  74580. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  74581. var parsedCamera = parsedData.cameras[index];
  74582. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  74583. container.cameras.push(camera);
  74584. log += (index === 0 ? "\n\tCameras:" : "");
  74585. log += "\n\t\t" + camera.toString(fullDetails);
  74586. }
  74587. }
  74588. // Animation Groups
  74589. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  74590. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  74591. var parsedAnimationGroup = parsedData.animationGroups[index];
  74592. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  74593. container.animationGroups.push(animationGroup);
  74594. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  74595. log += "\n\t\t" + animationGroup.toString(fullDetails);
  74596. }
  74597. }
  74598. // Browsing all the graph to connect the dots
  74599. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  74600. var camera = scene.cameras[index];
  74601. if (camera._waitingParentId) {
  74602. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  74603. camera._waitingParentId = null;
  74604. }
  74605. }
  74606. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74607. var light_1 = scene.lights[index];
  74608. if (light_1 && light_1._waitingParentId) {
  74609. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  74610. light_1._waitingParentId = null;
  74611. }
  74612. }
  74613. // Connect parents & children and parse actions
  74614. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  74615. var transformNode = scene.transformNodes[index];
  74616. if (transformNode._waitingParentId) {
  74617. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  74618. transformNode._waitingParentId = null;
  74619. }
  74620. }
  74621. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74622. var mesh = scene.meshes[index];
  74623. if (mesh._waitingParentId) {
  74624. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  74625. mesh._waitingParentId = null;
  74626. }
  74627. }
  74628. // freeze world matrix application
  74629. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74630. var currentMesh = scene.meshes[index];
  74631. if (currentMesh._waitingFreezeWorldMatrix) {
  74632. currentMesh.freezeWorldMatrix();
  74633. currentMesh._waitingFreezeWorldMatrix = null;
  74634. }
  74635. else {
  74636. currentMesh.computeWorldMatrix(true);
  74637. }
  74638. }
  74639. // Lights exclusions / inclusions
  74640. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  74641. var light_2 = scene.lights[index];
  74642. // Excluded check
  74643. if (light_2._excludedMeshesIds.length > 0) {
  74644. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  74645. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  74646. if (excludedMesh) {
  74647. light_2.excludedMeshes.push(excludedMesh);
  74648. }
  74649. }
  74650. light_2._excludedMeshesIds = [];
  74651. }
  74652. // Included check
  74653. if (light_2._includedOnlyMeshesIds.length > 0) {
  74654. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  74655. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  74656. if (includedOnlyMesh) {
  74657. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  74658. }
  74659. }
  74660. light_2._includedOnlyMeshesIds = [];
  74661. }
  74662. }
  74663. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  74664. // Actions (scene) Done last as it can access other objects.
  74665. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74666. var mesh = scene.meshes[index];
  74667. if (mesh._waitingActions) {
  74668. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  74669. mesh._waitingActions = null;
  74670. }
  74671. }
  74672. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  74673. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  74674. }
  74675. if (!addToScene) {
  74676. container.removeAllFromScene();
  74677. }
  74678. }
  74679. catch (err) {
  74680. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  74681. if (onError) {
  74682. onError(msg, err);
  74683. }
  74684. else {
  74685. BABYLON.Tools.Log(msg);
  74686. throw err;
  74687. }
  74688. }
  74689. finally {
  74690. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74691. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74692. }
  74693. }
  74694. return container;
  74695. };
  74696. BABYLON.SceneLoader.RegisterPlugin({
  74697. name: "babylon.js",
  74698. extensions: ".babylon",
  74699. canDirectLoad: function (data) {
  74700. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  74701. return true;
  74702. }
  74703. return false;
  74704. },
  74705. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74706. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74707. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74708. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74709. // and avoid problems with multiple concurrent .babylon loads.
  74710. var log = "importMesh has failed JSON parse";
  74711. try {
  74712. var parsedData = JSON.parse(data);
  74713. log = "";
  74714. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74715. if (!meshesNames) {
  74716. meshesNames = null;
  74717. }
  74718. else if (!Array.isArray(meshesNames)) {
  74719. meshesNames = [meshesNames];
  74720. }
  74721. var hierarchyIds = new Array();
  74722. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74723. var loadedSkeletonsIds = [];
  74724. var loadedMaterialsIds = [];
  74725. var index;
  74726. var cache;
  74727. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74728. var parsedMesh = parsedData.meshes[index];
  74729. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74730. if (meshesNames !== null) {
  74731. // Remove found mesh name from list.
  74732. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74733. }
  74734. //Geometry?
  74735. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74736. //does the file contain geometries?
  74737. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74738. //find the correct geometry and add it to the scene
  74739. var found = false;
  74740. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74741. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74742. return;
  74743. }
  74744. else {
  74745. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74746. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74747. switch (geometryType) {
  74748. case "boxes":
  74749. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74750. break;
  74751. case "spheres":
  74752. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74753. break;
  74754. case "cylinders":
  74755. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74756. break;
  74757. case "toruses":
  74758. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74759. break;
  74760. case "grounds":
  74761. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74762. break;
  74763. case "planes":
  74764. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74765. break;
  74766. case "torusKnots":
  74767. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74768. break;
  74769. case "vertexData":
  74770. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74771. break;
  74772. }
  74773. found = true;
  74774. }
  74775. });
  74776. }
  74777. });
  74778. if (found === false) {
  74779. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74780. }
  74781. }
  74782. }
  74783. // Material ?
  74784. if (parsedMesh.materialId) {
  74785. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74786. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74787. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74788. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74789. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74790. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74791. var subMatId = parsedMultiMaterial.materials[matIndex];
  74792. loadedMaterialsIds.push(subMatId);
  74793. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74794. if (mat) {
  74795. log += "\n\tMaterial " + mat.toString(fullDetails);
  74796. }
  74797. }
  74798. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74799. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74800. if (mmat) {
  74801. materialFound = true;
  74802. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74803. }
  74804. break;
  74805. }
  74806. }
  74807. }
  74808. if (materialFound === false) {
  74809. loadedMaterialsIds.push(parsedMesh.materialId);
  74810. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74811. if (!mat) {
  74812. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74813. }
  74814. else {
  74815. log += "\n\tMaterial " + mat.toString(fullDetails);
  74816. }
  74817. }
  74818. }
  74819. // Skeleton ?
  74820. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74821. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74822. if (skeletonAlreadyLoaded === false) {
  74823. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74824. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74825. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74826. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74827. skeletons.push(skeleton);
  74828. loadedSkeletonsIds.push(parsedSkeleton.id);
  74829. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74830. }
  74831. }
  74832. }
  74833. }
  74834. // Morph targets ?
  74835. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74836. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74837. var managerData = _a[_i];
  74838. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74839. }
  74840. }
  74841. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74842. meshes.push(mesh);
  74843. log += "\n\tMesh " + mesh.toString(fullDetails);
  74844. }
  74845. }
  74846. // Connecting parents
  74847. var currentMesh;
  74848. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74849. currentMesh = scene.meshes[index];
  74850. if (currentMesh._waitingParentId) {
  74851. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74852. currentMesh._waitingParentId = null;
  74853. }
  74854. }
  74855. // freeze and compute world matrix application
  74856. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74857. currentMesh = scene.meshes[index];
  74858. if (currentMesh._waitingFreezeWorldMatrix) {
  74859. currentMesh.freezeWorldMatrix();
  74860. currentMesh._waitingFreezeWorldMatrix = null;
  74861. }
  74862. else {
  74863. currentMesh.computeWorldMatrix(true);
  74864. }
  74865. }
  74866. }
  74867. // Particles
  74868. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74869. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74870. if (parser) {
  74871. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74872. var parsedParticleSystem = parsedData.particleSystems[index];
  74873. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74874. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74875. }
  74876. }
  74877. }
  74878. }
  74879. return true;
  74880. }
  74881. catch (err) {
  74882. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74883. if (onError) {
  74884. onError(msg, err);
  74885. }
  74886. else {
  74887. BABYLON.Tools.Log(msg);
  74888. throw err;
  74889. }
  74890. }
  74891. finally {
  74892. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74893. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74894. }
  74895. }
  74896. return false;
  74897. },
  74898. load: function (scene, data, rootUrl, onError) {
  74899. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74900. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74901. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74902. // and avoid problems with multiple concurrent .babylon loads.
  74903. var log = "importScene has failed JSON parse";
  74904. try {
  74905. var parsedData = JSON.parse(data);
  74906. log = "";
  74907. // Scene
  74908. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74909. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74910. }
  74911. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74912. scene.autoClear = parsedData.autoClear;
  74913. }
  74914. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74915. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74916. }
  74917. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74918. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74919. }
  74920. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74921. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74922. }
  74923. // Fog
  74924. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74925. scene.fogMode = parsedData.fogMode;
  74926. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74927. scene.fogStart = parsedData.fogStart;
  74928. scene.fogEnd = parsedData.fogEnd;
  74929. scene.fogDensity = parsedData.fogDensity;
  74930. log += "\tFog mode for scene: ";
  74931. switch (scene.fogMode) {
  74932. // getters not compiling, so using hardcoded
  74933. case 1:
  74934. log += "exp\n";
  74935. break;
  74936. case 2:
  74937. log += "exp2\n";
  74938. break;
  74939. case 3:
  74940. log += "linear\n";
  74941. break;
  74942. }
  74943. }
  74944. //Physics
  74945. if (parsedData.physicsEnabled) {
  74946. var physicsPlugin;
  74947. if (parsedData.physicsEngine === "cannon") {
  74948. physicsPlugin = new BABYLON.CannonJSPlugin();
  74949. }
  74950. else if (parsedData.physicsEngine === "oimo") {
  74951. physicsPlugin = new BABYLON.OimoJSPlugin();
  74952. }
  74953. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74954. //else - default engine, which is currently oimo
  74955. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74956. scene.enablePhysics(physicsGravity, physicsPlugin);
  74957. }
  74958. // Metadata
  74959. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74960. scene.metadata = parsedData.metadata;
  74961. }
  74962. //collisions, if defined. otherwise, default is true
  74963. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74964. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74965. }
  74966. scene.workerCollisions = !!parsedData.workerCollisions;
  74967. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74968. if (!container) {
  74969. return false;
  74970. }
  74971. if (parsedData.autoAnimate) {
  74972. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74973. }
  74974. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74975. scene.setActiveCameraByID(parsedData.activeCameraID);
  74976. }
  74977. // Environment texture
  74978. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74979. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74980. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74981. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74982. if (parsedData.environmentTextureRotationY) {
  74983. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74984. }
  74985. scene.environmentTexture = hdrTexture;
  74986. }
  74987. else {
  74988. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74989. if (parsedData.environmentTextureRotationY) {
  74990. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74991. }
  74992. scene.environmentTexture = cubeTexture;
  74993. }
  74994. if (parsedData.createDefaultSkybox === true) {
  74995. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74996. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74997. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74998. }
  74999. }
  75000. // Finish
  75001. return true;
  75002. }
  75003. catch (err) {
  75004. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  75005. if (onError) {
  75006. onError(msg, err);
  75007. }
  75008. else {
  75009. BABYLON.Tools.Log(msg);
  75010. throw err;
  75011. }
  75012. }
  75013. finally {
  75014. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  75015. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  75016. }
  75017. }
  75018. return false;
  75019. },
  75020. loadAssetContainer: function (scene, data, rootUrl, onError) {
  75021. var container = loadAssetContainer(scene, data, rootUrl, onError);
  75022. return container;
  75023. }
  75024. });
  75025. })(BABYLON || (BABYLON = {}));
  75026. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  75027. var BABYLON;
  75028. (function (BABYLON) {
  75029. var FilesInput = /** @class */ (function () {
  75030. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  75031. this.onProcessFileCallback = function () { return true; };
  75032. this._engine = engine;
  75033. this._currentScene = scene;
  75034. this._sceneLoadedCallback = sceneLoadedCallback;
  75035. this._progressCallback = progressCallback;
  75036. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  75037. this._textureLoadingCallback = textureLoadingCallback;
  75038. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  75039. this._onReloadCallback = onReloadCallback;
  75040. this._errorCallback = errorCallback;
  75041. }
  75042. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  75043. var _this = this;
  75044. if (elementToMonitor) {
  75045. this._elementToMonitor = elementToMonitor;
  75046. this._dragEnterHandler = function (e) { _this.drag(e); };
  75047. this._dragOverHandler = function (e) { _this.drag(e); };
  75048. this._dropHandler = function (e) { _this.drop(e); };
  75049. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  75050. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  75051. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  75052. }
  75053. };
  75054. FilesInput.prototype.dispose = function () {
  75055. if (!this._elementToMonitor) {
  75056. return;
  75057. }
  75058. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  75059. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  75060. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  75061. };
  75062. FilesInput.prototype.renderFunction = function () {
  75063. if (this._additionalRenderLoopLogicCallback) {
  75064. this._additionalRenderLoopLogicCallback();
  75065. }
  75066. if (this._currentScene) {
  75067. if (this._textureLoadingCallback) {
  75068. var remaining = this._currentScene.getWaitingItemsCount();
  75069. if (remaining > 0) {
  75070. this._textureLoadingCallback(remaining);
  75071. }
  75072. }
  75073. this._currentScene.render();
  75074. }
  75075. };
  75076. FilesInput.prototype.drag = function (e) {
  75077. e.stopPropagation();
  75078. e.preventDefault();
  75079. };
  75080. FilesInput.prototype.drop = function (eventDrop) {
  75081. eventDrop.stopPropagation();
  75082. eventDrop.preventDefault();
  75083. this.loadFiles(eventDrop);
  75084. };
  75085. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  75086. var _this = this;
  75087. var reader = folder.createReader();
  75088. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  75089. reader.readEntries(function (entries) {
  75090. remaining.count += entries.length;
  75091. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  75092. var entry = entries_1[_i];
  75093. if (entry.isFile) {
  75094. entry.file(function (file) {
  75095. file.correctName = relativePath + file.name;
  75096. files.push(file);
  75097. if (--remaining.count === 0) {
  75098. callback();
  75099. }
  75100. });
  75101. }
  75102. else if (entry.isDirectory) {
  75103. _this._traverseFolder(entry, files, remaining, callback);
  75104. }
  75105. }
  75106. if (--remaining.count) {
  75107. callback();
  75108. }
  75109. });
  75110. };
  75111. FilesInput.prototype._processFiles = function (files) {
  75112. for (var i = 0; i < files.length; i++) {
  75113. var name = files[i].correctName.toLowerCase();
  75114. var extension = name.split('.').pop();
  75115. if (!this.onProcessFileCallback(files[i], name, extension)) {
  75116. continue;
  75117. }
  75118. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  75119. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  75120. this._sceneFileToLoad = files[i];
  75121. }
  75122. FilesInput.FilesToLoad[name] = files[i];
  75123. }
  75124. };
  75125. FilesInput.prototype.loadFiles = function (event) {
  75126. var _this = this;
  75127. // Handling data transfer via drag'n'drop
  75128. if (event && event.dataTransfer && event.dataTransfer.files) {
  75129. this._filesToLoad = event.dataTransfer.files;
  75130. }
  75131. // Handling files from input files
  75132. if (event && event.target && event.target.files) {
  75133. this._filesToLoad = event.target.files;
  75134. }
  75135. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  75136. return;
  75137. }
  75138. if (this._startingProcessingFilesCallback) {
  75139. this._startingProcessingFilesCallback(this._filesToLoad);
  75140. }
  75141. if (this._filesToLoad && this._filesToLoad.length > 0) {
  75142. var files_1 = new Array();
  75143. var folders = [];
  75144. var items = event.dataTransfer ? event.dataTransfer.items : null;
  75145. for (var i = 0; i < this._filesToLoad.length; i++) {
  75146. var fileToLoad = this._filesToLoad[i];
  75147. var name_1 = fileToLoad.name.toLowerCase();
  75148. var entry = void 0;
  75149. fileToLoad.correctName = name_1;
  75150. if (items) {
  75151. var item = items[i];
  75152. if (item.getAsEntry) {
  75153. entry = item.getAsEntry();
  75154. }
  75155. else if (item.webkitGetAsEntry) {
  75156. entry = item.webkitGetAsEntry();
  75157. }
  75158. }
  75159. if (!entry) {
  75160. files_1.push(fileToLoad);
  75161. }
  75162. else {
  75163. if (entry.isDirectory) {
  75164. folders.push(entry);
  75165. }
  75166. else {
  75167. files_1.push(fileToLoad);
  75168. }
  75169. }
  75170. }
  75171. if (folders.length === 0) {
  75172. this._processFiles(files_1);
  75173. this._processReload();
  75174. }
  75175. else {
  75176. var remaining = { count: folders.length };
  75177. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  75178. var folder = folders_1[_i];
  75179. this._traverseFolder(folder, files_1, remaining, function () {
  75180. _this._processFiles(files_1);
  75181. if (remaining.count === 0) {
  75182. _this._processReload();
  75183. }
  75184. });
  75185. }
  75186. }
  75187. }
  75188. };
  75189. FilesInput.prototype._processReload = function () {
  75190. if (this._onReloadCallback) {
  75191. this._onReloadCallback(this._sceneFileToLoad);
  75192. }
  75193. else {
  75194. this.reload();
  75195. }
  75196. };
  75197. FilesInput.prototype.reload = function () {
  75198. var _this = this;
  75199. // If a scene file has been provided
  75200. if (this._sceneFileToLoad) {
  75201. if (this._currentScene) {
  75202. if (BABYLON.Tools.errorsCount > 0) {
  75203. BABYLON.Tools.ClearLogCache();
  75204. }
  75205. this._engine.stopRenderLoop();
  75206. }
  75207. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  75208. if (_this._progressCallback) {
  75209. _this._progressCallback(progress);
  75210. }
  75211. }).then(function (scene) {
  75212. if (_this._currentScene) {
  75213. _this._currentScene.dispose();
  75214. }
  75215. _this._currentScene = scene;
  75216. if (_this._sceneLoadedCallback) {
  75217. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  75218. }
  75219. // Wait for textures and shaders to be ready
  75220. _this._currentScene.executeWhenReady(function () {
  75221. _this._engine.runRenderLoop(function () {
  75222. _this.renderFunction();
  75223. });
  75224. });
  75225. }).catch(function (error) {
  75226. if (_this._errorCallback) {
  75227. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  75228. }
  75229. });
  75230. }
  75231. else {
  75232. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  75233. }
  75234. };
  75235. FilesInput.FilesToLoad = {};
  75236. return FilesInput;
  75237. }());
  75238. BABYLON.FilesInput = FilesInput;
  75239. })(BABYLON || (BABYLON = {}));
  75240. //# sourceMappingURL=babylon.filesInput.js.map
  75241. var BABYLON;
  75242. (function (BABYLON) {
  75243. var Tags = /** @class */ (function () {
  75244. function Tags() {
  75245. }
  75246. Tags.EnableFor = function (obj) {
  75247. obj._tags = obj._tags || {};
  75248. obj.hasTags = function () {
  75249. return Tags.HasTags(obj);
  75250. };
  75251. obj.addTags = function (tagsString) {
  75252. return Tags.AddTagsTo(obj, tagsString);
  75253. };
  75254. obj.removeTags = function (tagsString) {
  75255. return Tags.RemoveTagsFrom(obj, tagsString);
  75256. };
  75257. obj.matchesTagsQuery = function (tagsQuery) {
  75258. return Tags.MatchesQuery(obj, tagsQuery);
  75259. };
  75260. };
  75261. Tags.DisableFor = function (obj) {
  75262. delete obj._tags;
  75263. delete obj.hasTags;
  75264. delete obj.addTags;
  75265. delete obj.removeTags;
  75266. delete obj.matchesTagsQuery;
  75267. };
  75268. Tags.HasTags = function (obj) {
  75269. if (!obj._tags) {
  75270. return false;
  75271. }
  75272. return !BABYLON.Tools.IsEmpty(obj._tags);
  75273. };
  75274. Tags.GetTags = function (obj, asString) {
  75275. if (asString === void 0) { asString = true; }
  75276. if (!obj._tags) {
  75277. return null;
  75278. }
  75279. if (asString) {
  75280. var tagsArray = [];
  75281. for (var tag in obj._tags) {
  75282. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  75283. tagsArray.push(tag);
  75284. }
  75285. }
  75286. return tagsArray.join(" ");
  75287. }
  75288. else {
  75289. return obj._tags;
  75290. }
  75291. };
  75292. // the tags 'true' and 'false' are reserved and cannot be used as tags
  75293. // a tag cannot start with '||', '&&', and '!'
  75294. // it cannot contain whitespaces
  75295. Tags.AddTagsTo = function (obj, tagsString) {
  75296. if (!tagsString) {
  75297. return;
  75298. }
  75299. if (typeof tagsString !== "string") {
  75300. return;
  75301. }
  75302. var tags = tagsString.split(" ");
  75303. tags.forEach(function (tag, index, array) {
  75304. Tags._AddTagTo(obj, tag);
  75305. });
  75306. };
  75307. Tags._AddTagTo = function (obj, tag) {
  75308. tag = tag.trim();
  75309. if (tag === "" || tag === "true" || tag === "false") {
  75310. return;
  75311. }
  75312. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  75313. return;
  75314. }
  75315. Tags.EnableFor(obj);
  75316. obj._tags[tag] = true;
  75317. };
  75318. Tags.RemoveTagsFrom = function (obj, tagsString) {
  75319. if (!Tags.HasTags(obj)) {
  75320. return;
  75321. }
  75322. var tags = tagsString.split(" ");
  75323. for (var t in tags) {
  75324. Tags._RemoveTagFrom(obj, tags[t]);
  75325. }
  75326. };
  75327. Tags._RemoveTagFrom = function (obj, tag) {
  75328. delete obj._tags[tag];
  75329. };
  75330. Tags.MatchesQuery = function (obj, tagsQuery) {
  75331. if (tagsQuery === undefined) {
  75332. return true;
  75333. }
  75334. if (tagsQuery === "") {
  75335. return Tags.HasTags(obj);
  75336. }
  75337. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  75338. };
  75339. return Tags;
  75340. }());
  75341. BABYLON.Tags = Tags;
  75342. })(BABYLON || (BABYLON = {}));
  75343. //# sourceMappingURL=babylon.tags.js.map
  75344. var BABYLON;
  75345. (function (BABYLON) {
  75346. /**
  75347. * Class used to evalaute queries containing `and` and `or` operators
  75348. */
  75349. var AndOrNotEvaluator = /** @class */ (function () {
  75350. function AndOrNotEvaluator() {
  75351. }
  75352. /**
  75353. * Evaluate a query
  75354. * @param query defines the query to evaluate
  75355. * @param evaluateCallback defines the callback used to filter result
  75356. * @returns true if the query matches
  75357. */
  75358. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  75359. if (!query.match(/\([^\(\)]*\)/g)) {
  75360. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  75361. }
  75362. else {
  75363. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  75364. // remove parenthesis
  75365. r = r.slice(1, r.length - 1);
  75366. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  75367. });
  75368. }
  75369. if (query === "true") {
  75370. return true;
  75371. }
  75372. if (query === "false") {
  75373. return false;
  75374. }
  75375. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  75376. };
  75377. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  75378. evaluateCallback = evaluateCallback || (function (r) {
  75379. return r === "true" ? true : false;
  75380. });
  75381. var result;
  75382. var or = parenthesisContent.split("||");
  75383. for (var i in or) {
  75384. if (or.hasOwnProperty(i)) {
  75385. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  75386. var and = ori.split("&&");
  75387. if (and.length > 1) {
  75388. for (var j = 0; j < and.length; ++j) {
  75389. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  75390. if (andj !== "true" && andj !== "false") {
  75391. if (andj[0] === "!") {
  75392. result = !evaluateCallback(andj.substring(1));
  75393. }
  75394. else {
  75395. result = evaluateCallback(andj);
  75396. }
  75397. }
  75398. else {
  75399. result = andj === "true" ? true : false;
  75400. }
  75401. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  75402. ori = "false";
  75403. break;
  75404. }
  75405. }
  75406. }
  75407. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  75408. result = true;
  75409. break;
  75410. }
  75411. // result equals false (or undefined)
  75412. if (ori !== "true" && ori !== "false") {
  75413. if (ori[0] === "!") {
  75414. result = !evaluateCallback(ori.substring(1));
  75415. }
  75416. else {
  75417. result = evaluateCallback(ori);
  75418. }
  75419. }
  75420. else {
  75421. result = ori === "true" ? true : false;
  75422. }
  75423. }
  75424. }
  75425. // the whole parenthesis scope is replaced by 'true' or 'false'
  75426. return result ? "true" : "false";
  75427. };
  75428. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  75429. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  75430. // remove whitespaces
  75431. r = r.replace(/[\s]/g, function () { return ""; });
  75432. return r.length % 2 ? "!" : "";
  75433. });
  75434. booleanString = booleanString.trim();
  75435. if (booleanString === "!true") {
  75436. booleanString = "false";
  75437. }
  75438. else if (booleanString === "!false") {
  75439. booleanString = "true";
  75440. }
  75441. return booleanString;
  75442. };
  75443. return AndOrNotEvaluator;
  75444. }());
  75445. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  75446. })(BABYLON || (BABYLON = {}));
  75447. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  75448. var BABYLON;
  75449. (function (BABYLON) {
  75450. /**
  75451. * Class used to enable access to IndexedDB
  75452. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  75453. */
  75454. var Database = /** @class */ (function () {
  75455. /**
  75456. * Creates a new Database
  75457. * @param urlToScene defines the url to load the scene
  75458. * @param callbackManifestChecked defines the callback to use when manifest is checked
  75459. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  75460. */
  75461. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  75462. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  75463. var _this = this;
  75464. // Handling various flavors of prefixed version of IndexedDB
  75465. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  75466. this.callbackManifestChecked = callbackManifestChecked;
  75467. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  75468. this.db = null;
  75469. this._enableSceneOffline = false;
  75470. this._enableTexturesOffline = false;
  75471. this.manifestVersionFound = 0;
  75472. this.mustUpdateRessources = false;
  75473. this.hasReachedQuota = false;
  75474. if (!Database.IDBStorageEnabled) {
  75475. this.callbackManifestChecked(true);
  75476. }
  75477. else {
  75478. if (disableManifestCheck) {
  75479. this._enableSceneOffline = true;
  75480. this._enableTexturesOffline = true;
  75481. this.manifestVersionFound = 1;
  75482. BABYLON.Tools.SetImmediate(function () {
  75483. _this.callbackManifestChecked(true);
  75484. });
  75485. }
  75486. else {
  75487. this._checkManifestFile();
  75488. }
  75489. }
  75490. }
  75491. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  75492. /**
  75493. * Gets a boolean indicating if scene must be saved in the database
  75494. */
  75495. get: function () {
  75496. return this._enableSceneOffline;
  75497. },
  75498. enumerable: true,
  75499. configurable: true
  75500. });
  75501. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  75502. /**
  75503. * Gets a boolean indicating if textures must be saved in the database
  75504. */
  75505. get: function () {
  75506. return this._enableTexturesOffline;
  75507. },
  75508. enumerable: true,
  75509. configurable: true
  75510. });
  75511. Database.prototype._checkManifestFile = function () {
  75512. var _this = this;
  75513. var noManifestFile = function () {
  75514. _this._enableSceneOffline = false;
  75515. _this._enableTexturesOffline = false;
  75516. _this.callbackManifestChecked(false);
  75517. };
  75518. var timeStampUsed = false;
  75519. var manifestURL = this.currentSceneUrl + ".manifest";
  75520. var xhr = new XMLHttpRequest();
  75521. if (navigator.onLine) {
  75522. // Adding a timestamp to by-pass browsers' cache
  75523. timeStampUsed = true;
  75524. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  75525. }
  75526. xhr.open("GET", manifestURL, true);
  75527. xhr.addEventListener("load", function () {
  75528. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  75529. try {
  75530. var manifestFile = JSON.parse(xhr.response);
  75531. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  75532. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  75533. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  75534. _this.manifestVersionFound = manifestFile.version;
  75535. }
  75536. if (_this.callbackManifestChecked) {
  75537. _this.callbackManifestChecked(true);
  75538. }
  75539. }
  75540. catch (ex) {
  75541. noManifestFile();
  75542. }
  75543. }
  75544. else {
  75545. noManifestFile();
  75546. }
  75547. }, false);
  75548. xhr.addEventListener("error", function (event) {
  75549. if (timeStampUsed) {
  75550. timeStampUsed = false;
  75551. // Let's retry without the timeStamp
  75552. // It could fail when coupled with HTML5 Offline API
  75553. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  75554. xhr.open("GET", retryManifestURL, true);
  75555. xhr.send();
  75556. }
  75557. else {
  75558. noManifestFile();
  75559. }
  75560. }, false);
  75561. try {
  75562. xhr.send();
  75563. }
  75564. catch (ex) {
  75565. BABYLON.Tools.Error("Error on XHR send request.");
  75566. this.callbackManifestChecked(false);
  75567. }
  75568. };
  75569. /**
  75570. * Open the database and make it available
  75571. * @param successCallback defines the callback to call on success
  75572. * @param errorCallback defines the callback to call on error
  75573. */
  75574. Database.prototype.openAsync = function (successCallback, errorCallback) {
  75575. var _this = this;
  75576. var handleError = function () {
  75577. _this.isSupported = false;
  75578. if (errorCallback)
  75579. errorCallback();
  75580. };
  75581. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  75582. // Your browser doesn't support IndexedDB
  75583. this.isSupported = false;
  75584. if (errorCallback)
  75585. errorCallback();
  75586. }
  75587. else {
  75588. // If the DB hasn't been opened or created yet
  75589. if (!this.db) {
  75590. this.hasReachedQuota = false;
  75591. this.isSupported = true;
  75592. var request = this.idbFactory.open("babylonjs", 1);
  75593. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  75594. request.onerror = function (event) {
  75595. handleError();
  75596. };
  75597. // executes when a version change transaction cannot complete due to other active transactions
  75598. request.onblocked = function (event) {
  75599. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  75600. handleError();
  75601. };
  75602. // DB has been opened successfully
  75603. request.onsuccess = function (event) {
  75604. _this.db = request.result;
  75605. successCallback();
  75606. };
  75607. // Initialization of the DB. Creating Scenes & Textures stores
  75608. request.onupgradeneeded = function (event) {
  75609. _this.db = (event.target).result;
  75610. if (_this.db) {
  75611. try {
  75612. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  75613. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  75614. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  75615. }
  75616. catch (ex) {
  75617. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  75618. handleError();
  75619. }
  75620. }
  75621. };
  75622. }
  75623. // DB has already been created and opened
  75624. else {
  75625. if (successCallback)
  75626. successCallback();
  75627. }
  75628. }
  75629. };
  75630. /**
  75631. * Loads an image from the database
  75632. * @param url defines the url to load from
  75633. * @param image defines the target DOM image
  75634. */
  75635. Database.prototype.loadImageFromDB = function (url, image) {
  75636. var _this = this;
  75637. var completeURL = Database._ReturnFullUrlLocation(url);
  75638. var saveAndLoadImage = function () {
  75639. if (!_this.hasReachedQuota && _this.db !== null) {
  75640. // the texture is not yet in the DB, let's try to save it
  75641. _this._saveImageIntoDBAsync(completeURL, image);
  75642. }
  75643. // If the texture is not in the DB and we've reached the DB quota limit
  75644. // let's load it directly from the web
  75645. else {
  75646. image.src = url;
  75647. }
  75648. };
  75649. if (!this.mustUpdateRessources) {
  75650. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  75651. }
  75652. // First time we're download the images or update requested in the manifest file by a version change
  75653. else {
  75654. saveAndLoadImage();
  75655. }
  75656. };
  75657. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  75658. if (this.isSupported && this.db !== null) {
  75659. var texture;
  75660. var transaction = this.db.transaction(["textures"]);
  75661. transaction.onabort = function (event) {
  75662. image.src = url;
  75663. };
  75664. transaction.oncomplete = function (event) {
  75665. var blobTextureURL;
  75666. if (texture) {
  75667. var URL = window.URL || window.webkitURL;
  75668. blobTextureURL = URL.createObjectURL(texture.data);
  75669. image.onerror = function () {
  75670. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  75671. image.src = url;
  75672. };
  75673. image.src = blobTextureURL;
  75674. }
  75675. else {
  75676. notInDBCallback();
  75677. }
  75678. };
  75679. var getRequest = transaction.objectStore("textures").get(url);
  75680. getRequest.onsuccess = function (event) {
  75681. texture = (event.target).result;
  75682. };
  75683. getRequest.onerror = function (event) {
  75684. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  75685. image.src = url;
  75686. };
  75687. }
  75688. else {
  75689. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75690. image.src = url;
  75691. }
  75692. };
  75693. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  75694. var _this = this;
  75695. if (this.isSupported) {
  75696. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  75697. var generateBlobUrl = function () {
  75698. var blobTextureURL;
  75699. if (blob) {
  75700. var URL = window.URL || window.webkitURL;
  75701. try {
  75702. blobTextureURL = URL.createObjectURL(blob);
  75703. }
  75704. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75705. catch (ex) {
  75706. blobTextureURL = URL.createObjectURL(blob);
  75707. }
  75708. }
  75709. if (blobTextureURL) {
  75710. image.src = blobTextureURL;
  75711. }
  75712. };
  75713. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75714. var xhr = new XMLHttpRequest(), blob;
  75715. xhr.open("GET", url, true);
  75716. xhr.responseType = "blob";
  75717. xhr.addEventListener("load", function () {
  75718. if (xhr.status === 200 && _this.db) {
  75719. // Blob as response (XHR2)
  75720. blob = xhr.response;
  75721. var transaction = _this.db.transaction(["textures"], "readwrite");
  75722. // the transaction could abort because of a QuotaExceededError error
  75723. transaction.onabort = function (event) {
  75724. try {
  75725. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75726. var srcElement = (event.srcElement || event.target);
  75727. var error = srcElement.error;
  75728. if (error && error.name === "QuotaExceededError") {
  75729. _this.hasReachedQuota = true;
  75730. }
  75731. }
  75732. catch (ex) { }
  75733. generateBlobUrl();
  75734. };
  75735. transaction.oncomplete = function (event) {
  75736. generateBlobUrl();
  75737. };
  75738. var newTexture = { textureUrl: url, data: blob };
  75739. try {
  75740. // Put the blob into the dabase
  75741. var addRequest = transaction.objectStore("textures").put(newTexture);
  75742. addRequest.onsuccess = function (event) {
  75743. };
  75744. addRequest.onerror = function (event) {
  75745. generateBlobUrl();
  75746. };
  75747. }
  75748. catch (ex) {
  75749. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75750. if (ex.code === 25) {
  75751. Database.IsUASupportingBlobStorage = false;
  75752. }
  75753. image.src = url;
  75754. }
  75755. }
  75756. else {
  75757. image.src = url;
  75758. }
  75759. }, false);
  75760. xhr.addEventListener("error", function (event) {
  75761. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75762. image.src = url;
  75763. }, false);
  75764. xhr.send();
  75765. }
  75766. else {
  75767. image.src = url;
  75768. }
  75769. }
  75770. else {
  75771. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75772. image.src = url;
  75773. }
  75774. };
  75775. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75776. var _this = this;
  75777. var updateVersion = function () {
  75778. // the version is not yet in the DB or we need to update it
  75779. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75780. };
  75781. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75782. };
  75783. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75784. var _this = this;
  75785. if (this.isSupported && this.db) {
  75786. var version;
  75787. try {
  75788. var transaction = this.db.transaction(["versions"]);
  75789. transaction.oncomplete = function (event) {
  75790. if (version) {
  75791. // If the version in the JSON file is different from the version in DB
  75792. if (_this.manifestVersionFound !== version.data) {
  75793. _this.mustUpdateRessources = true;
  75794. updateInDBCallback();
  75795. }
  75796. else {
  75797. callback(version.data);
  75798. }
  75799. }
  75800. // version was not found in DB
  75801. else {
  75802. _this.mustUpdateRessources = true;
  75803. updateInDBCallback();
  75804. }
  75805. };
  75806. transaction.onabort = function (event) {
  75807. callback(-1);
  75808. };
  75809. var getRequest = transaction.objectStore("versions").get(url);
  75810. getRequest.onsuccess = function (event) {
  75811. version = (event.target).result;
  75812. };
  75813. getRequest.onerror = function (event) {
  75814. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75815. callback(-1);
  75816. };
  75817. }
  75818. catch (ex) {
  75819. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75820. callback(-1);
  75821. }
  75822. }
  75823. else {
  75824. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75825. callback(-1);
  75826. }
  75827. };
  75828. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75829. var _this = this;
  75830. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75831. try {
  75832. // Open a transaction to the database
  75833. var transaction = this.db.transaction(["versions"], "readwrite");
  75834. // the transaction could abort because of a QuotaExceededError error
  75835. transaction.onabort = function (event) {
  75836. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75837. var error = event.srcElement['error'];
  75838. if (error && error.name === "QuotaExceededError") {
  75839. _this.hasReachedQuota = true;
  75840. }
  75841. }
  75842. catch (ex) { }
  75843. callback(-1);
  75844. };
  75845. transaction.oncomplete = function (event) {
  75846. callback(_this.manifestVersionFound);
  75847. };
  75848. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75849. // Put the scene into the database
  75850. var addRequest = transaction.objectStore("versions").put(newVersion);
  75851. addRequest.onsuccess = function (event) {
  75852. };
  75853. addRequest.onerror = function (event) {
  75854. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75855. };
  75856. }
  75857. catch (ex) {
  75858. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75859. callback(-1);
  75860. }
  75861. }
  75862. else {
  75863. callback(-1);
  75864. }
  75865. };
  75866. /**
  75867. * Loads a file from database
  75868. * @param url defines the URL to load from
  75869. * @param sceneLoaded defines a callback to call on success
  75870. * @param progressCallBack defines a callback to call when progress changed
  75871. * @param errorCallback defines a callback to call on error
  75872. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75873. */
  75874. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75875. var _this = this;
  75876. var completeUrl = Database._ReturnFullUrlLocation(url);
  75877. var saveAndLoadFile = function () {
  75878. // the scene is not yet in the DB, let's try to save it
  75879. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75880. };
  75881. this._checkVersionFromDB(completeUrl, function (version) {
  75882. if (version !== -1) {
  75883. if (!_this.mustUpdateRessources) {
  75884. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75885. }
  75886. else {
  75887. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75888. }
  75889. }
  75890. else {
  75891. if (errorCallback) {
  75892. errorCallback();
  75893. }
  75894. }
  75895. });
  75896. };
  75897. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75898. if (this.isSupported && this.db) {
  75899. var targetStore;
  75900. if (url.indexOf(".babylon") !== -1) {
  75901. targetStore = "scenes";
  75902. }
  75903. else {
  75904. targetStore = "textures";
  75905. }
  75906. var file;
  75907. var transaction = this.db.transaction([targetStore]);
  75908. transaction.oncomplete = function (event) {
  75909. if (file) {
  75910. callback(file.data);
  75911. }
  75912. // file was not found in DB
  75913. else {
  75914. notInDBCallback();
  75915. }
  75916. };
  75917. transaction.onabort = function (event) {
  75918. notInDBCallback();
  75919. };
  75920. var getRequest = transaction.objectStore(targetStore).get(url);
  75921. getRequest.onsuccess = function (event) {
  75922. file = (event.target).result;
  75923. };
  75924. getRequest.onerror = function (event) {
  75925. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75926. notInDBCallback();
  75927. };
  75928. }
  75929. else {
  75930. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75931. callback();
  75932. }
  75933. };
  75934. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75935. var _this = this;
  75936. if (this.isSupported) {
  75937. var targetStore;
  75938. if (url.indexOf(".babylon") !== -1) {
  75939. targetStore = "scenes";
  75940. }
  75941. else {
  75942. targetStore = "textures";
  75943. }
  75944. // Create XHR
  75945. var xhr = new XMLHttpRequest();
  75946. var fileData;
  75947. xhr.open("GET", url + "?" + Date.now(), true);
  75948. if (useArrayBuffer) {
  75949. xhr.responseType = "arraybuffer";
  75950. }
  75951. if (progressCallback) {
  75952. xhr.onprogress = progressCallback;
  75953. }
  75954. xhr.addEventListener("load", function () {
  75955. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75956. // Blob as response (XHR2)
  75957. //fileData = xhr.responseText;
  75958. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75959. if (!_this.hasReachedQuota && _this.db) {
  75960. // Open a transaction to the database
  75961. var transaction = _this.db.transaction([targetStore], "readwrite");
  75962. // the transaction could abort because of a QuotaExceededError error
  75963. transaction.onabort = function (event) {
  75964. try {
  75965. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75966. var error = event.srcElement['error'];
  75967. if (error && error.name === "QuotaExceededError") {
  75968. _this.hasReachedQuota = true;
  75969. }
  75970. }
  75971. catch (ex) { }
  75972. callback(fileData);
  75973. };
  75974. transaction.oncomplete = function (event) {
  75975. callback(fileData);
  75976. };
  75977. var newFile;
  75978. if (targetStore === "scenes") {
  75979. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75980. }
  75981. else {
  75982. newFile = { textureUrl: url, data: fileData };
  75983. }
  75984. try {
  75985. // Put the scene into the database
  75986. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75987. addRequest.onsuccess = function (event) {
  75988. };
  75989. addRequest.onerror = function (event) {
  75990. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75991. };
  75992. }
  75993. catch (ex) {
  75994. callback(fileData);
  75995. }
  75996. }
  75997. else {
  75998. callback(fileData);
  75999. }
  76000. }
  76001. else {
  76002. if (xhr.status >= 400 && errorCallback) {
  76003. errorCallback(xhr);
  76004. }
  76005. else {
  76006. callback();
  76007. }
  76008. }
  76009. }, false);
  76010. xhr.addEventListener("error", function (event) {
  76011. BABYLON.Tools.Error("error on XHR request.");
  76012. callback();
  76013. }, false);
  76014. xhr.send();
  76015. }
  76016. else {
  76017. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  76018. callback();
  76019. }
  76020. };
  76021. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  76022. Database.IsUASupportingBlobStorage = true;
  76023. /** Gets a boolean indicating if Database storate is enabled */
  76024. Database.IDBStorageEnabled = true;
  76025. Database._ParseURL = function (url) {
  76026. var a = document.createElement('a');
  76027. a.href = url;
  76028. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  76029. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  76030. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  76031. return absLocation;
  76032. };
  76033. Database._ReturnFullUrlLocation = function (url) {
  76034. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  76035. return (Database._ParseURL(window.location.href) + url);
  76036. }
  76037. else {
  76038. return url;
  76039. }
  76040. };
  76041. return Database;
  76042. }());
  76043. BABYLON.Database = Database;
  76044. })(BABYLON || (BABYLON = {}));
  76045. //# sourceMappingURL=babylon.database.js.map
  76046. var BABYLON;
  76047. (function (BABYLON) {
  76048. var FresnelParameters = /** @class */ (function () {
  76049. function FresnelParameters() {
  76050. this._isEnabled = true;
  76051. this.leftColor = BABYLON.Color3.White();
  76052. this.rightColor = BABYLON.Color3.Black();
  76053. this.bias = 0;
  76054. this.power = 1;
  76055. }
  76056. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  76057. get: function () {
  76058. return this._isEnabled;
  76059. },
  76060. set: function (value) {
  76061. if (this._isEnabled === value) {
  76062. return;
  76063. }
  76064. this._isEnabled = value;
  76065. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  76066. },
  76067. enumerable: true,
  76068. configurable: true
  76069. });
  76070. FresnelParameters.prototype.clone = function () {
  76071. var newFresnelParameters = new FresnelParameters();
  76072. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  76073. return newFresnelParameters;
  76074. };
  76075. FresnelParameters.prototype.serialize = function () {
  76076. var serializationObject = {};
  76077. serializationObject.isEnabled = this.isEnabled;
  76078. serializationObject.leftColor = this.leftColor.asArray();
  76079. serializationObject.rightColor = this.rightColor.asArray();
  76080. serializationObject.bias = this.bias;
  76081. serializationObject.power = this.power;
  76082. return serializationObject;
  76083. };
  76084. FresnelParameters.Parse = function (parsedFresnelParameters) {
  76085. var fresnelParameters = new FresnelParameters();
  76086. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  76087. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  76088. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  76089. fresnelParameters.bias = parsedFresnelParameters.bias;
  76090. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  76091. return fresnelParameters;
  76092. };
  76093. return FresnelParameters;
  76094. }());
  76095. BABYLON.FresnelParameters = FresnelParameters;
  76096. })(BABYLON || (BABYLON = {}));
  76097. //# sourceMappingURL=babylon.fresnelParameters.js.map
  76098. var BABYLON;
  76099. (function (BABYLON) {
  76100. var MultiMaterial = /** @class */ (function (_super) {
  76101. __extends(MultiMaterial, _super);
  76102. function MultiMaterial(name, scene) {
  76103. var _this = _super.call(this, name, scene, true) || this;
  76104. scene.multiMaterials.push(_this);
  76105. _this.subMaterials = new Array();
  76106. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  76107. return _this;
  76108. }
  76109. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  76110. get: function () {
  76111. return this._subMaterials;
  76112. },
  76113. set: function (value) {
  76114. this._subMaterials = value;
  76115. this._hookArray(value);
  76116. },
  76117. enumerable: true,
  76118. configurable: true
  76119. });
  76120. MultiMaterial.prototype._hookArray = function (array) {
  76121. var _this = this;
  76122. var oldPush = array.push;
  76123. array.push = function () {
  76124. var items = [];
  76125. for (var _i = 0; _i < arguments.length; _i++) {
  76126. items[_i] = arguments[_i];
  76127. }
  76128. var result = oldPush.apply(array, items);
  76129. _this._markAllSubMeshesAsTexturesDirty();
  76130. return result;
  76131. };
  76132. var oldSplice = array.splice;
  76133. array.splice = function (index, deleteCount) {
  76134. var deleted = oldSplice.apply(array, [index, deleteCount]);
  76135. _this._markAllSubMeshesAsTexturesDirty();
  76136. return deleted;
  76137. };
  76138. };
  76139. // Properties
  76140. MultiMaterial.prototype.getSubMaterial = function (index) {
  76141. if (index < 0 || index >= this.subMaterials.length) {
  76142. return this.getScene().defaultMaterial;
  76143. }
  76144. return this.subMaterials[index];
  76145. };
  76146. MultiMaterial.prototype.getActiveTextures = function () {
  76147. var _a;
  76148. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  76149. if (subMaterial) {
  76150. return subMaterial.getActiveTextures();
  76151. }
  76152. else {
  76153. return [];
  76154. }
  76155. }));
  76156. };
  76157. // Methods
  76158. MultiMaterial.prototype.getClassName = function () {
  76159. return "MultiMaterial";
  76160. };
  76161. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76162. for (var index = 0; index < this.subMaterials.length; index++) {
  76163. var subMaterial = this.subMaterials[index];
  76164. if (subMaterial) {
  76165. if (subMaterial.storeEffectOnSubMeshes) {
  76166. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  76167. return false;
  76168. }
  76169. continue;
  76170. }
  76171. if (!subMaterial.isReady(mesh)) {
  76172. return false;
  76173. }
  76174. }
  76175. }
  76176. return true;
  76177. };
  76178. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  76179. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  76180. for (var index = 0; index < this.subMaterials.length; index++) {
  76181. var subMaterial = null;
  76182. var current = this.subMaterials[index];
  76183. if (cloneChildren && current) {
  76184. subMaterial = current.clone(name + "-" + current.name);
  76185. }
  76186. else {
  76187. subMaterial = this.subMaterials[index];
  76188. }
  76189. newMultiMaterial.subMaterials.push(subMaterial);
  76190. }
  76191. return newMultiMaterial;
  76192. };
  76193. MultiMaterial.prototype.serialize = function () {
  76194. var serializationObject = {};
  76195. serializationObject.name = this.name;
  76196. serializationObject.id = this.id;
  76197. if (BABYLON.Tags) {
  76198. serializationObject.tags = BABYLON.Tags.GetTags(this);
  76199. }
  76200. serializationObject.materials = [];
  76201. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  76202. var subMat = this.subMaterials[matIndex];
  76203. if (subMat) {
  76204. serializationObject.materials.push(subMat.id);
  76205. }
  76206. else {
  76207. serializationObject.materials.push(null);
  76208. }
  76209. }
  76210. return serializationObject;
  76211. };
  76212. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76213. var scene = this.getScene();
  76214. if (!scene) {
  76215. return;
  76216. }
  76217. var index = scene.multiMaterials.indexOf(this);
  76218. if (index >= 0) {
  76219. scene.multiMaterials.splice(index, 1);
  76220. }
  76221. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  76222. };
  76223. return MultiMaterial;
  76224. }(BABYLON.Material));
  76225. BABYLON.MultiMaterial = MultiMaterial;
  76226. })(BABYLON || (BABYLON = {}));
  76227. //# sourceMappingURL=babylon.multiMaterial.js.map
  76228. var BABYLON;
  76229. (function (BABYLON) {
  76230. /**
  76231. * Manage the touch inputs to control the movement of a free camera.
  76232. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76233. */
  76234. var FreeCameraTouchInput = /** @class */ (function () {
  76235. function FreeCameraTouchInput() {
  76236. /**
  76237. * Defines the touch sensibility for rotation.
  76238. * The higher the faster.
  76239. */
  76240. this.touchAngularSensibility = 200000.0;
  76241. /**
  76242. * Defines the touch sensibility for move.
  76243. * The higher the faster.
  76244. */
  76245. this.touchMoveSensibility = 250.0;
  76246. this._offsetX = null;
  76247. this._offsetY = null;
  76248. this._pointerPressed = new Array();
  76249. }
  76250. /**
  76251. * Attach the input controls to a specific dom element to get the input from.
  76252. * @param element Defines the element the controls should be listened from
  76253. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76254. */
  76255. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  76256. var _this = this;
  76257. var previousPosition = null;
  76258. if (this._pointerInput === undefined) {
  76259. this._onLostFocus = function (evt) {
  76260. _this._offsetX = null;
  76261. _this._offsetY = null;
  76262. };
  76263. this._pointerInput = function (p, s) {
  76264. var evt = p.event;
  76265. if (evt.pointerType === "mouse") {
  76266. return;
  76267. }
  76268. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  76269. if (!noPreventDefault) {
  76270. evt.preventDefault();
  76271. }
  76272. _this._pointerPressed.push(evt.pointerId);
  76273. if (_this._pointerPressed.length !== 1) {
  76274. return;
  76275. }
  76276. previousPosition = {
  76277. x: evt.clientX,
  76278. y: evt.clientY
  76279. };
  76280. }
  76281. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  76282. if (!noPreventDefault) {
  76283. evt.preventDefault();
  76284. }
  76285. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76286. if (index === -1) {
  76287. return;
  76288. }
  76289. _this._pointerPressed.splice(index, 1);
  76290. if (index != 0) {
  76291. return;
  76292. }
  76293. previousPosition = null;
  76294. _this._offsetX = null;
  76295. _this._offsetY = null;
  76296. }
  76297. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  76298. if (!noPreventDefault) {
  76299. evt.preventDefault();
  76300. }
  76301. if (!previousPosition) {
  76302. return;
  76303. }
  76304. var index = _this._pointerPressed.indexOf(evt.pointerId);
  76305. if (index != 0) {
  76306. return;
  76307. }
  76308. _this._offsetX = evt.clientX - previousPosition.x;
  76309. _this._offsetY = -(evt.clientY - previousPosition.y);
  76310. }
  76311. };
  76312. }
  76313. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  76314. if (this._onLostFocus) {
  76315. element.addEventListener("blur", this._onLostFocus);
  76316. }
  76317. };
  76318. /**
  76319. * Detach the current controls from the specified dom element.
  76320. * @param element Defines the element to stop listening the inputs from
  76321. */
  76322. FreeCameraTouchInput.prototype.detachControl = function (element) {
  76323. if (this._pointerInput && element) {
  76324. if (this._observer) {
  76325. this.camera.getScene().onPointerObservable.remove(this._observer);
  76326. this._observer = null;
  76327. }
  76328. if (this._onLostFocus) {
  76329. element.removeEventListener("blur", this._onLostFocus);
  76330. this._onLostFocus = null;
  76331. }
  76332. this._pointerPressed = [];
  76333. this._offsetX = null;
  76334. this._offsetY = null;
  76335. }
  76336. };
  76337. /**
  76338. * Update the current camera state depending on the inputs that have been used this frame.
  76339. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76340. */
  76341. FreeCameraTouchInput.prototype.checkInputs = function () {
  76342. if (this._offsetX && this._offsetY) {
  76343. var camera = this.camera;
  76344. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  76345. if (this._pointerPressed.length > 1) {
  76346. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  76347. }
  76348. else {
  76349. var speed = camera._computeLocalCameraSpeed();
  76350. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  76351. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  76352. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  76353. }
  76354. }
  76355. };
  76356. /**
  76357. * Gets the class name of the current intput.
  76358. * @returns the class name
  76359. */
  76360. FreeCameraTouchInput.prototype.getClassName = function () {
  76361. return "FreeCameraTouchInput";
  76362. };
  76363. /**
  76364. * Get the friendly name associated with the input class.
  76365. * @returns the input friendly name
  76366. */
  76367. FreeCameraTouchInput.prototype.getSimpleName = function () {
  76368. return "touch";
  76369. };
  76370. __decorate([
  76371. BABYLON.serialize()
  76372. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  76373. __decorate([
  76374. BABYLON.serialize()
  76375. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  76376. return FreeCameraTouchInput;
  76377. }());
  76378. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  76379. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  76380. })(BABYLON || (BABYLON = {}));
  76381. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  76382. var BABYLON;
  76383. (function (BABYLON) {
  76384. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  76385. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  76386. });
  76387. /**
  76388. * This represents a FPS type of camera controlled by touch.
  76389. * This is like a universal camera minus the Gamepad controls.
  76390. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76391. */
  76392. var TouchCamera = /** @class */ (function (_super) {
  76393. __extends(TouchCamera, _super);
  76394. /**
  76395. * Instantiates a new touch camera.
  76396. * This represents a FPS type of camera controlled by touch.
  76397. * This is like a universal camera minus the Gamepad controls.
  76398. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  76399. * @param name Define the name of the camera in the scene
  76400. * @param position Define the start position of the camera in the scene
  76401. * @param scene Define the scene the camera belongs to
  76402. */
  76403. function TouchCamera(name, position, scene) {
  76404. var _this = _super.call(this, name, position, scene) || this;
  76405. _this.inputs.addTouch();
  76406. _this._setupInputs();
  76407. return _this;
  76408. }
  76409. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  76410. /**
  76411. * Defines the touch sensibility for rotation.
  76412. * The higher the faster.
  76413. */
  76414. get: function () {
  76415. var touch = this.inputs.attached["touch"];
  76416. if (touch)
  76417. return touch.touchAngularSensibility;
  76418. return 0;
  76419. },
  76420. set: function (value) {
  76421. var touch = this.inputs.attached["touch"];
  76422. if (touch)
  76423. touch.touchAngularSensibility = value;
  76424. },
  76425. enumerable: true,
  76426. configurable: true
  76427. });
  76428. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  76429. /**
  76430. * Defines the touch sensibility for move.
  76431. * The higher the faster.
  76432. */
  76433. get: function () {
  76434. var touch = this.inputs.attached["touch"];
  76435. if (touch)
  76436. return touch.touchMoveSensibility;
  76437. return 0;
  76438. },
  76439. set: function (value) {
  76440. var touch = this.inputs.attached["touch"];
  76441. if (touch)
  76442. touch.touchMoveSensibility = value;
  76443. },
  76444. enumerable: true,
  76445. configurable: true
  76446. });
  76447. /**
  76448. * Gets the current object class name.
  76449. * @return the class name
  76450. */
  76451. TouchCamera.prototype.getClassName = function () {
  76452. return "TouchCamera";
  76453. };
  76454. /** @hidden */
  76455. TouchCamera.prototype._setupInputs = function () {
  76456. var mouse = this.inputs.attached["mouse"];
  76457. if (mouse) {
  76458. mouse.touchEnabled = false;
  76459. }
  76460. };
  76461. return TouchCamera;
  76462. }(BABYLON.FreeCamera));
  76463. BABYLON.TouchCamera = TouchCamera;
  76464. })(BABYLON || (BABYLON = {}));
  76465. //# sourceMappingURL=babylon.touchCamera.js.map
  76466. var BABYLON;
  76467. (function (BABYLON) {
  76468. var ProceduralTexture = /** @class */ (function (_super) {
  76469. __extends(ProceduralTexture, _super);
  76470. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  76471. if (fallbackTexture === void 0) { fallbackTexture = null; }
  76472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  76473. if (isCube === void 0) { isCube = false; }
  76474. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  76475. _this.isCube = isCube;
  76476. _this.isEnabled = true;
  76477. _this._currentRefreshId = -1;
  76478. _this._refreshRate = 1;
  76479. /**
  76480. * Event raised when the texture is generated
  76481. */
  76482. _this.onGeneratedObservable = new BABYLON.Observable();
  76483. _this._vertexBuffers = {};
  76484. _this._uniforms = new Array();
  76485. _this._samplers = new Array();
  76486. /** @hidden */
  76487. _this._textures = {};
  76488. _this._floats = {};
  76489. _this._ints = {};
  76490. _this._floatsArrays = {};
  76491. _this._colors3 = {};
  76492. _this._colors4 = {};
  76493. _this._vectors2 = {};
  76494. _this._vectors3 = {};
  76495. _this._matrices = {};
  76496. _this._fallbackTextureUsed = false;
  76497. _this._cachedDefines = "";
  76498. _this._contentUpdateId = -1;
  76499. scene = _this.getScene();
  76500. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  76501. if (!component) {
  76502. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  76503. scene._addComponent(component);
  76504. }
  76505. scene.proceduralTextures.push(_this);
  76506. _this._engine = scene.getEngine();
  76507. _this.name = name;
  76508. _this.isRenderTarget = true;
  76509. _this._size = size;
  76510. _this._generateMipMaps = generateMipMaps;
  76511. _this.setFragment(fragment);
  76512. _this._fallbackTexture = fallbackTexture;
  76513. if (isCube) {
  76514. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  76515. _this.setFloat("face", 0);
  76516. }
  76517. else {
  76518. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  76519. }
  76520. // VBO
  76521. var vertices = [];
  76522. vertices.push(1, 1);
  76523. vertices.push(-1, 1);
  76524. vertices.push(-1, -1);
  76525. vertices.push(1, -1);
  76526. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76527. _this._createIndexBuffer();
  76528. return _this;
  76529. }
  76530. /**
  76531. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  76532. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  76533. */
  76534. ProceduralTexture.prototype.getContent = function () {
  76535. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  76536. return this._contentData;
  76537. }
  76538. this._contentData = this.readPixels(0, 0, this._contentData);
  76539. this._contentUpdateId = this._currentRefreshId;
  76540. return this._contentData;
  76541. };
  76542. ProceduralTexture.prototype._createIndexBuffer = function () {
  76543. var engine = this._engine;
  76544. // Indices
  76545. var indices = [];
  76546. indices.push(0);
  76547. indices.push(1);
  76548. indices.push(2);
  76549. indices.push(0);
  76550. indices.push(2);
  76551. indices.push(3);
  76552. this._indexBuffer = engine.createIndexBuffer(indices);
  76553. };
  76554. /** @hidden */
  76555. ProceduralTexture.prototype._rebuild = function () {
  76556. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76557. if (vb) {
  76558. vb._rebuild();
  76559. }
  76560. this._createIndexBuffer();
  76561. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  76562. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  76563. }
  76564. };
  76565. ProceduralTexture.prototype.reset = function () {
  76566. if (this._effect === undefined) {
  76567. return;
  76568. }
  76569. var engine = this._engine;
  76570. engine._releaseEffect(this._effect);
  76571. };
  76572. ProceduralTexture.prototype._getDefines = function () {
  76573. return "";
  76574. };
  76575. ProceduralTexture.prototype.isReady = function () {
  76576. var _this = this;
  76577. var engine = this._engine;
  76578. var shaders;
  76579. if (!this._fragment) {
  76580. return false;
  76581. }
  76582. if (this._fallbackTextureUsed) {
  76583. return true;
  76584. }
  76585. var defines = this._getDefines();
  76586. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  76587. return true;
  76588. }
  76589. if (this._fragment.fragmentElement !== undefined) {
  76590. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  76591. }
  76592. else {
  76593. shaders = { vertex: "procedural", fragment: this._fragment };
  76594. }
  76595. this._cachedDefines = defines;
  76596. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  76597. _this.releaseInternalTexture();
  76598. if (_this._fallbackTexture) {
  76599. _this._texture = _this._fallbackTexture._texture;
  76600. if (_this._texture) {
  76601. _this._texture.incrementReferences();
  76602. }
  76603. }
  76604. _this._fallbackTextureUsed = true;
  76605. });
  76606. return this._effect.isReady();
  76607. };
  76608. ProceduralTexture.prototype.resetRefreshCounter = function () {
  76609. this._currentRefreshId = -1;
  76610. };
  76611. ProceduralTexture.prototype.setFragment = function (fragment) {
  76612. this._fragment = fragment;
  76613. };
  76614. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  76615. get: function () {
  76616. return this._refreshRate;
  76617. },
  76618. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  76619. set: function (value) {
  76620. this._refreshRate = value;
  76621. this.resetRefreshCounter();
  76622. },
  76623. enumerable: true,
  76624. configurable: true
  76625. });
  76626. /** @hidden */
  76627. ProceduralTexture.prototype._shouldRender = function () {
  76628. if (!this.isEnabled || !this.isReady() || !this._texture) {
  76629. if (this._texture) {
  76630. this._texture.isReady = false;
  76631. }
  76632. return false;
  76633. }
  76634. if (this._fallbackTextureUsed) {
  76635. return false;
  76636. }
  76637. if (this._currentRefreshId === -1) { // At least render once
  76638. this._currentRefreshId = 1;
  76639. return true;
  76640. }
  76641. if (this.refreshRate === this._currentRefreshId) {
  76642. this._currentRefreshId = 1;
  76643. return true;
  76644. }
  76645. this._currentRefreshId++;
  76646. return false;
  76647. };
  76648. ProceduralTexture.prototype.getRenderSize = function () {
  76649. return this._size;
  76650. };
  76651. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  76652. if (this._fallbackTextureUsed) {
  76653. return;
  76654. }
  76655. this.releaseInternalTexture();
  76656. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  76657. // Update properties
  76658. this._size = size;
  76659. this._generateMipMaps = generateMipMaps;
  76660. };
  76661. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  76662. if (this._uniforms.indexOf(uniformName) === -1) {
  76663. this._uniforms.push(uniformName);
  76664. }
  76665. };
  76666. ProceduralTexture.prototype.setTexture = function (name, texture) {
  76667. if (this._samplers.indexOf(name) === -1) {
  76668. this._samplers.push(name);
  76669. }
  76670. this._textures[name] = texture;
  76671. return this;
  76672. };
  76673. ProceduralTexture.prototype.setFloat = function (name, value) {
  76674. this._checkUniform(name);
  76675. this._floats[name] = value;
  76676. return this;
  76677. };
  76678. /**
  76679. * Set the value of an uniform to an integer value
  76680. * @param name defines the name of the uniform
  76681. * @param value defines the value to set
  76682. * @returns the current procedural texture
  76683. */
  76684. ProceduralTexture.prototype.setInt = function (name, value) {
  76685. this._checkUniform(name);
  76686. this._ints[name] = value;
  76687. return this;
  76688. };
  76689. ProceduralTexture.prototype.setFloats = function (name, value) {
  76690. this._checkUniform(name);
  76691. this._floatsArrays[name] = value;
  76692. return this;
  76693. };
  76694. ProceduralTexture.prototype.setColor3 = function (name, value) {
  76695. this._checkUniform(name);
  76696. this._colors3[name] = value;
  76697. return this;
  76698. };
  76699. ProceduralTexture.prototype.setColor4 = function (name, value) {
  76700. this._checkUniform(name);
  76701. this._colors4[name] = value;
  76702. return this;
  76703. };
  76704. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76705. this._checkUniform(name);
  76706. this._vectors2[name] = value;
  76707. return this;
  76708. };
  76709. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76710. this._checkUniform(name);
  76711. this._vectors3[name] = value;
  76712. return this;
  76713. };
  76714. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76715. this._checkUniform(name);
  76716. this._matrices[name] = value;
  76717. return this;
  76718. };
  76719. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76720. var scene = this.getScene();
  76721. if (!scene) {
  76722. return;
  76723. }
  76724. var engine = this._engine;
  76725. // Render
  76726. engine.enableEffect(this._effect);
  76727. engine.setState(false);
  76728. // Texture
  76729. for (var name in this._textures) {
  76730. this._effect.setTexture(name, this._textures[name]);
  76731. }
  76732. // Float
  76733. for (name in this._ints) {
  76734. this._effect.setInt(name, this._ints[name]);
  76735. }
  76736. // Float
  76737. for (name in this._floats) {
  76738. this._effect.setFloat(name, this._floats[name]);
  76739. }
  76740. // Floats
  76741. for (name in this._floatsArrays) {
  76742. this._effect.setArray(name, this._floatsArrays[name]);
  76743. }
  76744. // Color3
  76745. for (name in this._colors3) {
  76746. this._effect.setColor3(name, this._colors3[name]);
  76747. }
  76748. // Color4
  76749. for (name in this._colors4) {
  76750. var color = this._colors4[name];
  76751. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76752. }
  76753. // Vector2
  76754. for (name in this._vectors2) {
  76755. this._effect.setVector2(name, this._vectors2[name]);
  76756. }
  76757. // Vector3
  76758. for (name in this._vectors3) {
  76759. this._effect.setVector3(name, this._vectors3[name]);
  76760. }
  76761. // Matrix
  76762. for (name in this._matrices) {
  76763. this._effect.setMatrix(name, this._matrices[name]);
  76764. }
  76765. if (!this._texture) {
  76766. return;
  76767. }
  76768. if (this.isCube) {
  76769. for (var face = 0; face < 6; face++) {
  76770. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76771. // VBOs
  76772. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76773. this._effect.setFloat("face", face);
  76774. // Clear
  76775. engine.clear(scene.clearColor, true, true, true);
  76776. // Draw order
  76777. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76778. // Mipmaps
  76779. if (face === 5) {
  76780. engine.generateMipMapsForCubemap(this._texture);
  76781. }
  76782. }
  76783. }
  76784. else {
  76785. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76786. // VBOs
  76787. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76788. // Clear
  76789. engine.clear(scene.clearColor, true, true, true);
  76790. // Draw order
  76791. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76792. }
  76793. // Unbind
  76794. engine.unBindFramebuffer(this._texture, this.isCube);
  76795. if (this.onGenerated) {
  76796. this.onGenerated();
  76797. }
  76798. this.onGeneratedObservable.notifyObservers(this);
  76799. };
  76800. ProceduralTexture.prototype.clone = function () {
  76801. var textureSize = this.getSize();
  76802. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76803. // Base texture
  76804. newTexture.hasAlpha = this.hasAlpha;
  76805. newTexture.level = this.level;
  76806. // RenderTarget Texture
  76807. newTexture.coordinatesMode = this.coordinatesMode;
  76808. return newTexture;
  76809. };
  76810. ProceduralTexture.prototype.dispose = function () {
  76811. var scene = this.getScene();
  76812. if (!scene) {
  76813. return;
  76814. }
  76815. var index = scene.proceduralTextures.indexOf(this);
  76816. if (index >= 0) {
  76817. scene.proceduralTextures.splice(index, 1);
  76818. }
  76819. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76820. if (vertexBuffer) {
  76821. vertexBuffer.dispose();
  76822. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76823. }
  76824. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76825. this._indexBuffer = null;
  76826. }
  76827. _super.prototype.dispose.call(this);
  76828. };
  76829. __decorate([
  76830. BABYLON.serialize()
  76831. ], ProceduralTexture.prototype, "_size", void 0);
  76832. __decorate([
  76833. BABYLON.serialize()
  76834. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76835. __decorate([
  76836. BABYLON.serialize()
  76837. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76838. __decorate([
  76839. BABYLON.serialize()
  76840. ], ProceduralTexture.prototype, "refreshRate", null);
  76841. return ProceduralTexture;
  76842. }(BABYLON.Texture));
  76843. BABYLON.ProceduralTexture = ProceduralTexture;
  76844. })(BABYLON || (BABYLON = {}));
  76845. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76846. var BABYLON;
  76847. (function (BABYLON) {
  76848. /**
  76849. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76850. * in a given scene.
  76851. */
  76852. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76853. /**
  76854. * Creates a new instance of the component for the given scene
  76855. * @param scene Defines the scene to register the component in
  76856. */
  76857. function ProceduralTextureSceneComponent(scene) {
  76858. /**
  76859. * The component name helpfull to identify the component in the list of scene components.
  76860. */
  76861. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76862. this.scene = scene;
  76863. this.scene.proceduralTextures = new Array();
  76864. scene.layers = new Array();
  76865. }
  76866. /**
  76867. * Registers the component in a given scene
  76868. */
  76869. ProceduralTextureSceneComponent.prototype.register = function () {
  76870. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76871. };
  76872. /**
  76873. * Rebuilds the elements related to this component in case of
  76874. * context lost for instance.
  76875. */
  76876. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76877. // Nothing to do here.
  76878. };
  76879. /**
  76880. * Disposes the component and the associated ressources.
  76881. */
  76882. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76883. // Nothing to do here.
  76884. };
  76885. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76886. if (this.scene.proceduralTexturesEnabled) {
  76887. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76888. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76889. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76890. if (proceduralTexture._shouldRender()) {
  76891. proceduralTexture.render();
  76892. }
  76893. }
  76894. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76895. }
  76896. };
  76897. return ProceduralTextureSceneComponent;
  76898. }());
  76899. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76900. })(BABYLON || (BABYLON = {}));
  76901. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76902. var BABYLON;
  76903. (function (BABYLON) {
  76904. var CustomProceduralTexture = /** @class */ (function (_super) {
  76905. __extends(CustomProceduralTexture, _super);
  76906. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76907. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76908. _this._animate = true;
  76909. _this._time = 0;
  76910. _this._texturePath = texturePath;
  76911. //Try to load json
  76912. _this.loadJson(texturePath);
  76913. _this.refreshRate = 1;
  76914. return _this;
  76915. }
  76916. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76917. var _this = this;
  76918. var noConfigFile = function () {
  76919. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76920. try {
  76921. _this.setFragment(_this._texturePath);
  76922. }
  76923. catch (ex) {
  76924. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76925. }
  76926. };
  76927. var configFileUrl = jsonUrl + "/config.json";
  76928. var xhr = new XMLHttpRequest();
  76929. xhr.open("GET", configFileUrl, true);
  76930. xhr.addEventListener("load", function () {
  76931. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76932. try {
  76933. _this._config = JSON.parse(xhr.response);
  76934. _this.updateShaderUniforms();
  76935. _this.updateTextures();
  76936. _this.setFragment(_this._texturePath + "/custom");
  76937. _this._animate = _this._config.animate;
  76938. _this.refreshRate = _this._config.refreshrate;
  76939. }
  76940. catch (ex) {
  76941. noConfigFile();
  76942. }
  76943. }
  76944. else {
  76945. noConfigFile();
  76946. }
  76947. }, false);
  76948. xhr.addEventListener("error", function () {
  76949. noConfigFile();
  76950. }, false);
  76951. try {
  76952. xhr.send();
  76953. }
  76954. catch (ex) {
  76955. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76956. }
  76957. };
  76958. CustomProceduralTexture.prototype.isReady = function () {
  76959. if (!_super.prototype.isReady.call(this)) {
  76960. return false;
  76961. }
  76962. for (var name in this._textures) {
  76963. var texture = this._textures[name];
  76964. if (!texture.isReady()) {
  76965. return false;
  76966. }
  76967. }
  76968. return true;
  76969. };
  76970. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76971. var scene = this.getScene();
  76972. if (this._animate && scene) {
  76973. this._time += scene.getAnimationRatio() * 0.03;
  76974. this.updateShaderUniforms();
  76975. }
  76976. _super.prototype.render.call(this, useCameraPostProcess);
  76977. };
  76978. CustomProceduralTexture.prototype.updateTextures = function () {
  76979. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76980. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76981. }
  76982. };
  76983. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76984. if (this._config) {
  76985. for (var j = 0; j < this._config.uniforms.length; j++) {
  76986. var uniform = this._config.uniforms[j];
  76987. switch (uniform.type) {
  76988. case "float":
  76989. this.setFloat(uniform.name, uniform.value);
  76990. break;
  76991. case "color3":
  76992. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76993. break;
  76994. case "color4":
  76995. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76996. break;
  76997. case "vector2":
  76998. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76999. break;
  77000. case "vector3":
  77001. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  77002. break;
  77003. }
  77004. }
  77005. }
  77006. this.setFloat("time", this._time);
  77007. };
  77008. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  77009. get: function () {
  77010. return this._animate;
  77011. },
  77012. set: function (value) {
  77013. this._animate = value;
  77014. },
  77015. enumerable: true,
  77016. configurable: true
  77017. });
  77018. return CustomProceduralTexture;
  77019. }(BABYLON.ProceduralTexture));
  77020. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  77021. })(BABYLON || (BABYLON = {}));
  77022. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  77023. var BABYLON;
  77024. (function (BABYLON) {
  77025. /**
  77026. * Manage the gamepad inputs to control a free camera.
  77027. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77028. */
  77029. var FreeCameraGamepadInput = /** @class */ (function () {
  77030. function FreeCameraGamepadInput() {
  77031. /**
  77032. * Defines the gamepad rotation sensiblity.
  77033. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77034. */
  77035. this.gamepadAngularSensibility = 200;
  77036. /**
  77037. * Defines the gamepad move sensiblity.
  77038. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77039. */
  77040. this.gamepadMoveSensibility = 40;
  77041. this._cameraTransform = BABYLON.Matrix.Identity();
  77042. this._deltaTransform = BABYLON.Vector3.Zero();
  77043. this._vector3 = BABYLON.Vector3.Zero();
  77044. this._vector2 = BABYLON.Vector2.Zero();
  77045. }
  77046. /**
  77047. * Attach the input controls to a specific dom element to get the input from.
  77048. * @param element Defines the element the controls should be listened from
  77049. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77050. */
  77051. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77052. var _this = this;
  77053. var manager = this.camera.getScene().gamepadManager;
  77054. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77055. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77056. // prioritize XBOX gamepads.
  77057. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77058. _this.gamepad = gamepad;
  77059. }
  77060. }
  77061. });
  77062. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77063. if (_this.gamepad === gamepad) {
  77064. _this.gamepad = null;
  77065. }
  77066. });
  77067. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77068. };
  77069. /**
  77070. * Detach the current controls from the specified dom element.
  77071. * @param element Defines the element to stop listening the inputs from
  77072. */
  77073. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  77074. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77075. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77076. this.gamepad = null;
  77077. };
  77078. /**
  77079. * Update the current camera state depending on the inputs that have been used this frame.
  77080. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77081. */
  77082. FreeCameraGamepadInput.prototype.checkInputs = function () {
  77083. if (this.gamepad && this.gamepad.leftStick) {
  77084. var camera = this.camera;
  77085. var LSValues = this.gamepad.leftStick;
  77086. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  77087. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77088. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  77089. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  77090. var RSValues = this.gamepad.rightStick;
  77091. if (RSValues) {
  77092. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  77093. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  77094. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  77095. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  77096. }
  77097. else {
  77098. RSValues = { x: 0, y: 0 };
  77099. }
  77100. if (!camera.rotationQuaternion) {
  77101. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  77102. }
  77103. else {
  77104. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  77105. }
  77106. var speed = camera._computeLocalCameraSpeed() * 50.0;
  77107. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  77108. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  77109. camera.cameraDirection.addInPlace(this._deltaTransform);
  77110. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  77111. camera.cameraRotation.addInPlace(this._vector2);
  77112. }
  77113. };
  77114. /**
  77115. * Gets the class name of the current intput.
  77116. * @returns the class name
  77117. */
  77118. FreeCameraGamepadInput.prototype.getClassName = function () {
  77119. return "FreeCameraGamepadInput";
  77120. };
  77121. /**
  77122. * Get the friendly name associated with the input class.
  77123. * @returns the input friendly name
  77124. */
  77125. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  77126. return "gamepad";
  77127. };
  77128. __decorate([
  77129. BABYLON.serialize()
  77130. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  77131. __decorate([
  77132. BABYLON.serialize()
  77133. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77134. return FreeCameraGamepadInput;
  77135. }());
  77136. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  77137. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  77138. })(BABYLON || (BABYLON = {}));
  77139. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  77140. var BABYLON;
  77141. (function (BABYLON) {
  77142. /**
  77143. * Manage the gamepad inputs to control an arc rotate camera.
  77144. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77145. */
  77146. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  77147. function ArcRotateCameraGamepadInput() {
  77148. /**
  77149. * Defines the gamepad rotation sensiblity.
  77150. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  77151. */
  77152. this.gamepadRotationSensibility = 80;
  77153. /**
  77154. * Defines the gamepad move sensiblity.
  77155. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  77156. */
  77157. this.gamepadMoveSensibility = 40;
  77158. }
  77159. /**
  77160. * Attach the input controls to a specific dom element to get the input from.
  77161. * @param element Defines the element the controls should be listened from
  77162. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77163. */
  77164. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  77165. var _this = this;
  77166. var manager = this.camera.getScene().gamepadManager;
  77167. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  77168. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  77169. // prioritize XBOX gamepads.
  77170. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  77171. _this.gamepad = gamepad;
  77172. }
  77173. }
  77174. });
  77175. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  77176. if (_this.gamepad === gamepad) {
  77177. _this.gamepad = null;
  77178. }
  77179. });
  77180. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  77181. };
  77182. /**
  77183. * Detach the current controls from the specified dom element.
  77184. * @param element Defines the element to stop listening the inputs from
  77185. */
  77186. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  77187. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  77188. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  77189. this.gamepad = null;
  77190. };
  77191. /**
  77192. * Update the current camera state depending on the inputs that have been used this frame.
  77193. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77194. */
  77195. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  77196. if (this.gamepad) {
  77197. var camera = this.camera;
  77198. var RSValues = this.gamepad.rightStick;
  77199. if (RSValues) {
  77200. if (RSValues.x != 0) {
  77201. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  77202. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  77203. camera.inertialAlphaOffset += normalizedRX;
  77204. }
  77205. }
  77206. if (RSValues.y != 0) {
  77207. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  77208. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  77209. camera.inertialBetaOffset += normalizedRY;
  77210. }
  77211. }
  77212. }
  77213. var LSValues = this.gamepad.leftStick;
  77214. if (LSValues && LSValues.y != 0) {
  77215. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  77216. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  77217. this.camera.inertialRadiusOffset -= normalizedLY;
  77218. }
  77219. }
  77220. }
  77221. };
  77222. /**
  77223. * Gets the class name of the current intput.
  77224. * @returns the class name
  77225. */
  77226. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  77227. return "ArcRotateCameraGamepadInput";
  77228. };
  77229. /**
  77230. * Get the friendly name associated with the input class.
  77231. * @returns the input friendly name
  77232. */
  77233. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  77234. return "gamepad";
  77235. };
  77236. __decorate([
  77237. BABYLON.serialize()
  77238. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  77239. __decorate([
  77240. BABYLON.serialize()
  77241. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  77242. return ArcRotateCameraGamepadInput;
  77243. }());
  77244. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  77245. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  77246. })(BABYLON || (BABYLON = {}));
  77247. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  77248. var BABYLON;
  77249. (function (BABYLON) {
  77250. /**
  77251. * Manager for handling gamepads
  77252. */
  77253. var GamepadManager = /** @class */ (function () {
  77254. /**
  77255. * Initializes the gamepad manager
  77256. * @param _scene BabylonJS scene
  77257. */
  77258. function GamepadManager(_scene) {
  77259. var _this = this;
  77260. this._scene = _scene;
  77261. this._babylonGamepads = [];
  77262. this._oneGamepadConnected = false;
  77263. /** @hidden */
  77264. this._isMonitoring = false;
  77265. /**
  77266. * observable to be triggered when the gamepad controller has been disconnected
  77267. */
  77268. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  77269. if (!BABYLON.Tools.IsWindowObjectExist()) {
  77270. this._gamepadEventSupported = false;
  77271. }
  77272. else {
  77273. this._gamepadEventSupported = 'GamepadEvent' in window;
  77274. this._gamepadSupport = (navigator.getGamepads ||
  77275. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  77276. }
  77277. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  77278. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  77279. for (var i in _this._babylonGamepads) {
  77280. var gamepad = _this._babylonGamepads[i];
  77281. if (gamepad && gamepad._isConnected) {
  77282. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  77283. }
  77284. }
  77285. });
  77286. this._onGamepadConnectedEvent = function (evt) {
  77287. var gamepad = evt.gamepad;
  77288. if (gamepad.index in _this._babylonGamepads) {
  77289. if (_this._babylonGamepads[gamepad.index].isConnected) {
  77290. return;
  77291. }
  77292. }
  77293. var newGamepad;
  77294. if (_this._babylonGamepads[gamepad.index]) {
  77295. newGamepad = _this._babylonGamepads[gamepad.index];
  77296. newGamepad.browserGamepad = gamepad;
  77297. newGamepad._isConnected = true;
  77298. }
  77299. else {
  77300. newGamepad = _this._addNewGamepad(gamepad);
  77301. }
  77302. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77303. _this._startMonitoringGamepads();
  77304. };
  77305. this._onGamepadDisconnectedEvent = function (evt) {
  77306. var gamepad = evt.gamepad;
  77307. // Remove the gamepad from the list of gamepads to monitor.
  77308. for (var i in _this._babylonGamepads) {
  77309. if (_this._babylonGamepads[i].index === gamepad.index) {
  77310. var disconnectedGamepad = _this._babylonGamepads[i];
  77311. disconnectedGamepad._isConnected = false;
  77312. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  77313. break;
  77314. }
  77315. }
  77316. };
  77317. if (this._gamepadSupport) {
  77318. //first add already-connected gamepads
  77319. this._updateGamepadObjects();
  77320. if (this._babylonGamepads.length) {
  77321. this._startMonitoringGamepads();
  77322. }
  77323. // Checking if the gamepad connected event is supported (like in Firefox)
  77324. if (this._gamepadEventSupported) {
  77325. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  77326. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  77327. }
  77328. else {
  77329. this._startMonitoringGamepads();
  77330. }
  77331. }
  77332. }
  77333. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  77334. /**
  77335. * The gamepads in the game pad manager
  77336. */
  77337. get: function () {
  77338. return this._babylonGamepads;
  77339. },
  77340. enumerable: true,
  77341. configurable: true
  77342. });
  77343. /**
  77344. * Get the gamepad controllers based on type
  77345. * @param type The type of gamepad controller
  77346. * @returns Nullable gamepad
  77347. */
  77348. GamepadManager.prototype.getGamepadByType = function (type) {
  77349. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  77350. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  77351. var gamepad = _a[_i];
  77352. if (gamepad && gamepad.type === type) {
  77353. return gamepad;
  77354. }
  77355. }
  77356. return null;
  77357. };
  77358. /**
  77359. * Disposes the gamepad manager
  77360. */
  77361. GamepadManager.prototype.dispose = function () {
  77362. if (this._gamepadEventSupported) {
  77363. if (this._onGamepadConnectedEvent) {
  77364. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  77365. }
  77366. if (this._onGamepadDisconnectedEvent) {
  77367. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  77368. }
  77369. this._onGamepadConnectedEvent = null;
  77370. this._onGamepadDisconnectedEvent = null;
  77371. }
  77372. this._babylonGamepads.forEach(function (gamepad) {
  77373. gamepad.dispose();
  77374. });
  77375. this.onGamepadConnectedObservable.clear();
  77376. this.onGamepadDisconnectedObservable.clear();
  77377. this._oneGamepadConnected = false;
  77378. this._stopMonitoringGamepads();
  77379. this._babylonGamepads = [];
  77380. };
  77381. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  77382. if (!this._oneGamepadConnected) {
  77383. this._oneGamepadConnected = true;
  77384. }
  77385. var newGamepad;
  77386. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  77387. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  77388. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  77389. }
  77390. // if pose is supported, use the (WebVR) pose enabled controller
  77391. else if (gamepad.pose) {
  77392. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  77393. }
  77394. else {
  77395. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  77396. }
  77397. this._babylonGamepads[newGamepad.index] = newGamepad;
  77398. return newGamepad;
  77399. };
  77400. GamepadManager.prototype._startMonitoringGamepads = function () {
  77401. if (!this._isMonitoring) {
  77402. this._isMonitoring = true;
  77403. //back-comp
  77404. if (!this._scene) {
  77405. this._checkGamepadsStatus();
  77406. }
  77407. }
  77408. };
  77409. GamepadManager.prototype._stopMonitoringGamepads = function () {
  77410. this._isMonitoring = false;
  77411. };
  77412. /** @hidden */
  77413. GamepadManager.prototype._checkGamepadsStatus = function () {
  77414. var _this = this;
  77415. // Hack to be compatible Chrome
  77416. this._updateGamepadObjects();
  77417. for (var i in this._babylonGamepads) {
  77418. var gamepad = this._babylonGamepads[i];
  77419. if (!gamepad || !gamepad.isConnected) {
  77420. continue;
  77421. }
  77422. gamepad.update();
  77423. }
  77424. if (this._isMonitoring && !this._scene) {
  77425. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  77426. }
  77427. };
  77428. // This function is called only on Chrome, which does not properly support
  77429. // connection/disconnection events and forces you to recopy again the gamepad object
  77430. GamepadManager.prototype._updateGamepadObjects = function () {
  77431. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  77432. for (var i = 0; i < gamepads.length; i++) {
  77433. var gamepad = gamepads[i];
  77434. if (gamepad) {
  77435. if (!this._babylonGamepads[gamepad.index]) {
  77436. var newGamepad = this._addNewGamepad(gamepad);
  77437. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  77438. }
  77439. else {
  77440. // Forced to copy again this object for Chrome for unknown reason
  77441. this._babylonGamepads[i].browserGamepad = gamepad;
  77442. if (!this._babylonGamepads[i].isConnected) {
  77443. this._babylonGamepads[i]._isConnected = true;
  77444. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  77445. }
  77446. }
  77447. }
  77448. }
  77449. };
  77450. return GamepadManager;
  77451. }());
  77452. BABYLON.GamepadManager = GamepadManager;
  77453. })(BABYLON || (BABYLON = {}));
  77454. //# sourceMappingURL=babylon.gamepadManager.js.map
  77455. var BABYLON;
  77456. (function (BABYLON) {
  77457. /**
  77458. * Represents a gamepad control stick position
  77459. */
  77460. var StickValues = /** @class */ (function () {
  77461. /**
  77462. * Initializes the gamepad x and y control stick values
  77463. * @param x The x component of the gamepad control stick value
  77464. * @param y The y component of the gamepad control stick value
  77465. */
  77466. function StickValues(
  77467. /**
  77468. * The x component of the control stick
  77469. */
  77470. x,
  77471. /**
  77472. * The y component of the control stick
  77473. */
  77474. y) {
  77475. this.x = x;
  77476. this.y = y;
  77477. }
  77478. return StickValues;
  77479. }());
  77480. BABYLON.StickValues = StickValues;
  77481. /**
  77482. * Represents a gamepad
  77483. */
  77484. var Gamepad = /** @class */ (function () {
  77485. /**
  77486. * Initializes the gamepad
  77487. * @param id The id of the gamepad
  77488. * @param index The index of the gamepad
  77489. * @param browserGamepad The browser gamepad
  77490. * @param leftStickX The x component of the left joystick
  77491. * @param leftStickY The y component of the left joystick
  77492. * @param rightStickX The x component of the right joystick
  77493. * @param rightStickY The y component of the right joystick
  77494. */
  77495. function Gamepad(
  77496. /**
  77497. * The id of the gamepad
  77498. */
  77499. id,
  77500. /**
  77501. * The index of the gamepad
  77502. */
  77503. index,
  77504. /**
  77505. * The browser gamepad
  77506. */
  77507. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  77508. if (leftStickX === void 0) { leftStickX = 0; }
  77509. if (leftStickY === void 0) { leftStickY = 1; }
  77510. if (rightStickX === void 0) { rightStickX = 2; }
  77511. if (rightStickY === void 0) { rightStickY = 3; }
  77512. this.id = id;
  77513. this.index = index;
  77514. this.browserGamepad = browserGamepad;
  77515. this._leftStick = { x: 0, y: 0 };
  77516. this._rightStick = { x: 0, y: 0 };
  77517. /** @hidden */
  77518. this._isConnected = true;
  77519. /**
  77520. * Specifies whether the left control stick should be Y-inverted
  77521. */
  77522. this._invertLeftStickY = false;
  77523. this.type = Gamepad.GAMEPAD;
  77524. this._leftStickAxisX = leftStickX;
  77525. this._leftStickAxisY = leftStickY;
  77526. this._rightStickAxisX = rightStickX;
  77527. this._rightStickAxisY = rightStickY;
  77528. if (this.browserGamepad.axes.length >= 2) {
  77529. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77530. }
  77531. if (this.browserGamepad.axes.length >= 4) {
  77532. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77533. }
  77534. }
  77535. Object.defineProperty(Gamepad.prototype, "isConnected", {
  77536. /**
  77537. * Specifies if the gamepad has been connected
  77538. */
  77539. get: function () {
  77540. return this._isConnected;
  77541. },
  77542. enumerable: true,
  77543. configurable: true
  77544. });
  77545. /**
  77546. * Callback triggered when the left joystick has changed
  77547. * @param callback
  77548. */
  77549. Gamepad.prototype.onleftstickchanged = function (callback) {
  77550. this._onleftstickchanged = callback;
  77551. };
  77552. /**
  77553. * Callback triggered when the right joystick has changed
  77554. * @param callback
  77555. */
  77556. Gamepad.prototype.onrightstickchanged = function (callback) {
  77557. this._onrightstickchanged = callback;
  77558. };
  77559. Object.defineProperty(Gamepad.prototype, "leftStick", {
  77560. /**
  77561. * Gets the left joystick
  77562. */
  77563. get: function () {
  77564. return this._leftStick;
  77565. },
  77566. /**
  77567. * Sets the left joystick values
  77568. */
  77569. set: function (newValues) {
  77570. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  77571. this._onleftstickchanged(newValues);
  77572. }
  77573. this._leftStick = newValues;
  77574. },
  77575. enumerable: true,
  77576. configurable: true
  77577. });
  77578. Object.defineProperty(Gamepad.prototype, "rightStick", {
  77579. /**
  77580. * Gets the right joystick
  77581. */
  77582. get: function () {
  77583. return this._rightStick;
  77584. },
  77585. /**
  77586. * Sets the right joystick value
  77587. */
  77588. set: function (newValues) {
  77589. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  77590. this._onrightstickchanged(newValues);
  77591. }
  77592. this._rightStick = newValues;
  77593. },
  77594. enumerable: true,
  77595. configurable: true
  77596. });
  77597. /**
  77598. * Updates the gamepad joystick positions
  77599. */
  77600. Gamepad.prototype.update = function () {
  77601. if (this._leftStick) {
  77602. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  77603. if (this._invertLeftStickY) {
  77604. this.leftStick.y *= -1;
  77605. }
  77606. }
  77607. if (this._rightStick) {
  77608. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  77609. }
  77610. };
  77611. /**
  77612. * Disposes the gamepad
  77613. */
  77614. Gamepad.prototype.dispose = function () {
  77615. };
  77616. /**
  77617. * Represents a gamepad controller
  77618. */
  77619. Gamepad.GAMEPAD = 0;
  77620. /**
  77621. * Represents a generic controller
  77622. */
  77623. Gamepad.GENERIC = 1;
  77624. /**
  77625. * Represents an XBox controller
  77626. */
  77627. Gamepad.XBOX = 2;
  77628. /**
  77629. * Represents a pose-enabled controller
  77630. */
  77631. Gamepad.POSE_ENABLED = 3;
  77632. return Gamepad;
  77633. }());
  77634. BABYLON.Gamepad = Gamepad;
  77635. /**
  77636. * Represents a generic gamepad
  77637. */
  77638. var GenericPad = /** @class */ (function (_super) {
  77639. __extends(GenericPad, _super);
  77640. /**
  77641. * Initializes the generic gamepad
  77642. * @param id The id of the generic gamepad
  77643. * @param index The index of the generic gamepad
  77644. * @param browserGamepad The browser gamepad
  77645. */
  77646. function GenericPad(id, index, browserGamepad) {
  77647. var _this = _super.call(this, id, index, browserGamepad) || this;
  77648. /**
  77649. * Observable triggered when a button has been pressed
  77650. */
  77651. _this.onButtonDownObservable = new BABYLON.Observable();
  77652. /**
  77653. * Observable triggered when a button has been released
  77654. */
  77655. _this.onButtonUpObservable = new BABYLON.Observable();
  77656. _this.type = Gamepad.GENERIC;
  77657. _this._buttons = new Array(browserGamepad.buttons.length);
  77658. return _this;
  77659. }
  77660. /**
  77661. * Callback triggered when a button has been pressed
  77662. * @param callback Called when a button has been pressed
  77663. */
  77664. GenericPad.prototype.onbuttondown = function (callback) {
  77665. this._onbuttondown = callback;
  77666. };
  77667. /**
  77668. * Callback triggered when a button has been released
  77669. * @param callback Called when a button has been released
  77670. */
  77671. GenericPad.prototype.onbuttonup = function (callback) {
  77672. this._onbuttonup = callback;
  77673. };
  77674. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  77675. if (newValue !== currentValue) {
  77676. if (newValue === 1) {
  77677. if (this._onbuttondown) {
  77678. this._onbuttondown(buttonIndex);
  77679. }
  77680. this.onButtonDownObservable.notifyObservers(buttonIndex);
  77681. }
  77682. if (newValue === 0) {
  77683. if (this._onbuttonup) {
  77684. this._onbuttonup(buttonIndex);
  77685. }
  77686. this.onButtonUpObservable.notifyObservers(buttonIndex);
  77687. }
  77688. }
  77689. return newValue;
  77690. };
  77691. /**
  77692. * Updates the generic gamepad
  77693. */
  77694. GenericPad.prototype.update = function () {
  77695. _super.prototype.update.call(this);
  77696. for (var index = 0; index < this._buttons.length; index++) {
  77697. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  77698. }
  77699. };
  77700. /**
  77701. * Disposes the generic gamepad
  77702. */
  77703. GenericPad.prototype.dispose = function () {
  77704. _super.prototype.dispose.call(this);
  77705. this.onButtonDownObservable.clear();
  77706. this.onButtonUpObservable.clear();
  77707. };
  77708. return GenericPad;
  77709. }(Gamepad));
  77710. BABYLON.GenericPad = GenericPad;
  77711. })(BABYLON || (BABYLON = {}));
  77712. //# sourceMappingURL=babylon.gamepad.js.map
  77713. var BABYLON;
  77714. (function (BABYLON) {
  77715. /**
  77716. * Defines supported buttons for XBox360 compatible gamepads
  77717. */
  77718. var Xbox360Button;
  77719. (function (Xbox360Button) {
  77720. /** A */
  77721. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  77722. /** B */
  77723. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  77724. /** X */
  77725. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  77726. /** Y */
  77727. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  77728. /** Start */
  77729. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  77730. /** Back */
  77731. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  77732. /** Left button */
  77733. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  77734. /** Right button */
  77735. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  77736. /** Left stick */
  77737. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  77738. /** Right stick */
  77739. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  77740. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  77741. /** Defines values for XBox360 DPad */
  77742. var Xbox360Dpad;
  77743. (function (Xbox360Dpad) {
  77744. /** Up */
  77745. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  77746. /** Down */
  77747. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  77748. /** Left */
  77749. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  77750. /** Right */
  77751. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  77752. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  77753. /**
  77754. * Defines a XBox360 gamepad
  77755. */
  77756. var Xbox360Pad = /** @class */ (function (_super) {
  77757. __extends(Xbox360Pad, _super);
  77758. /**
  77759. * Creates a new XBox360 gamepad object
  77760. * @param id defines the id of this gamepad
  77761. * @param index defines its index
  77762. * @param gamepad defines the internal HTML gamepad object
  77763. * @param xboxOne defines if it is a XBox One gamepad
  77764. */
  77765. function Xbox360Pad(id, index, gamepad, xboxOne) {
  77766. if (xboxOne === void 0) { xboxOne = false; }
  77767. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  77768. _this._leftTrigger = 0;
  77769. _this._rightTrigger = 0;
  77770. /** Observable raised when a button is pressed */
  77771. _this.onButtonDownObservable = new BABYLON.Observable();
  77772. /** Observable raised when a button is released */
  77773. _this.onButtonUpObservable = new BABYLON.Observable();
  77774. /** Observable raised when a pad is pressed */
  77775. _this.onPadDownObservable = new BABYLON.Observable();
  77776. /** Observable raised when a pad is released */
  77777. _this.onPadUpObservable = new BABYLON.Observable();
  77778. _this._buttonA = 0;
  77779. _this._buttonB = 0;
  77780. _this._buttonX = 0;
  77781. _this._buttonY = 0;
  77782. _this._buttonBack = 0;
  77783. _this._buttonStart = 0;
  77784. _this._buttonLB = 0;
  77785. _this._buttonRB = 0;
  77786. _this._buttonLeftStick = 0;
  77787. _this._buttonRightStick = 0;
  77788. _this._dPadUp = 0;
  77789. _this._dPadDown = 0;
  77790. _this._dPadLeft = 0;
  77791. _this._dPadRight = 0;
  77792. _this._isXboxOnePad = false;
  77793. _this.type = BABYLON.Gamepad.XBOX;
  77794. _this._isXboxOnePad = xboxOne;
  77795. return _this;
  77796. }
  77797. /**
  77798. * Defines the callback to call when left trigger is pressed
  77799. * @param callback defines the callback to use
  77800. */
  77801. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  77802. this._onlefttriggerchanged = callback;
  77803. };
  77804. /**
  77805. * Defines the callback to call when right trigger is pressed
  77806. * @param callback defines the callback to use
  77807. */
  77808. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  77809. this._onrighttriggerchanged = callback;
  77810. };
  77811. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  77812. /**
  77813. * Gets the left trigger value
  77814. */
  77815. get: function () {
  77816. return this._leftTrigger;
  77817. },
  77818. /**
  77819. * Sets the left trigger value
  77820. */
  77821. set: function (newValue) {
  77822. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  77823. this._onlefttriggerchanged(newValue);
  77824. }
  77825. this._leftTrigger = newValue;
  77826. },
  77827. enumerable: true,
  77828. configurable: true
  77829. });
  77830. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  77831. /**
  77832. * Gets the right trigger value
  77833. */
  77834. get: function () {
  77835. return this._rightTrigger;
  77836. },
  77837. /**
  77838. * Sets the right trigger value
  77839. */
  77840. set: function (newValue) {
  77841. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  77842. this._onrighttriggerchanged(newValue);
  77843. }
  77844. this._rightTrigger = newValue;
  77845. },
  77846. enumerable: true,
  77847. configurable: true
  77848. });
  77849. /**
  77850. * Defines the callback to call when a button is pressed
  77851. * @param callback defines the callback to use
  77852. */
  77853. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77854. this._onbuttondown = callback;
  77855. };
  77856. /**
  77857. * Defines the callback to call when a button is released
  77858. * @param callback defines the callback to use
  77859. */
  77860. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77861. this._onbuttonup = callback;
  77862. };
  77863. /**
  77864. * Defines the callback to call when a pad is pressed
  77865. * @param callback defines the callback to use
  77866. */
  77867. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77868. this._ondpaddown = callback;
  77869. };
  77870. /**
  77871. * Defines the callback to call when a pad is released
  77872. * @param callback defines the callback to use
  77873. */
  77874. Xbox360Pad.prototype.ondpadup = function (callback) {
  77875. this._ondpadup = callback;
  77876. };
  77877. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77878. if (newValue !== currentValue) {
  77879. if (newValue === 1) {
  77880. if (this._onbuttondown) {
  77881. this._onbuttondown(buttonType);
  77882. }
  77883. this.onButtonDownObservable.notifyObservers(buttonType);
  77884. }
  77885. if (newValue === 0) {
  77886. if (this._onbuttonup) {
  77887. this._onbuttonup(buttonType);
  77888. }
  77889. this.onButtonUpObservable.notifyObservers(buttonType);
  77890. }
  77891. }
  77892. return newValue;
  77893. };
  77894. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77895. if (newValue !== currentValue) {
  77896. if (newValue === 1) {
  77897. if (this._ondpaddown) {
  77898. this._ondpaddown(buttonType);
  77899. }
  77900. this.onPadDownObservable.notifyObservers(buttonType);
  77901. }
  77902. if (newValue === 0) {
  77903. if (this._ondpadup) {
  77904. this._ondpadup(buttonType);
  77905. }
  77906. this.onPadUpObservable.notifyObservers(buttonType);
  77907. }
  77908. }
  77909. return newValue;
  77910. };
  77911. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77912. /**
  77913. * Gets the value of the `A` button
  77914. */
  77915. get: function () {
  77916. return this._buttonA;
  77917. },
  77918. /**
  77919. * Sets the value of the `A` button
  77920. */
  77921. set: function (value) {
  77922. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77923. },
  77924. enumerable: true,
  77925. configurable: true
  77926. });
  77927. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77928. /**
  77929. * Gets the value of the `B` button
  77930. */
  77931. get: function () {
  77932. return this._buttonB;
  77933. },
  77934. /**
  77935. * Sets the value of the `B` button
  77936. */
  77937. set: function (value) {
  77938. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77944. /**
  77945. * Gets the value of the `X` button
  77946. */
  77947. get: function () {
  77948. return this._buttonX;
  77949. },
  77950. /**
  77951. * Sets the value of the `X` button
  77952. */
  77953. set: function (value) {
  77954. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77955. },
  77956. enumerable: true,
  77957. configurable: true
  77958. });
  77959. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77960. /**
  77961. * Gets the value of the `Y` button
  77962. */
  77963. get: function () {
  77964. return this._buttonY;
  77965. },
  77966. /**
  77967. * Sets the value of the `Y` button
  77968. */
  77969. set: function (value) {
  77970. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77971. },
  77972. enumerable: true,
  77973. configurable: true
  77974. });
  77975. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77976. /**
  77977. * Gets the value of the `Start` button
  77978. */
  77979. get: function () {
  77980. return this._buttonStart;
  77981. },
  77982. /**
  77983. * Sets the value of the `Start` button
  77984. */
  77985. set: function (value) {
  77986. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77987. },
  77988. enumerable: true,
  77989. configurable: true
  77990. });
  77991. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77992. /**
  77993. * Gets the value of the `Back` button
  77994. */
  77995. get: function () {
  77996. return this._buttonBack;
  77997. },
  77998. /**
  77999. * Sets the value of the `Back` button
  78000. */
  78001. set: function (value) {
  78002. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  78003. },
  78004. enumerable: true,
  78005. configurable: true
  78006. });
  78007. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  78008. /**
  78009. * Gets the value of the `Left` button
  78010. */
  78011. get: function () {
  78012. return this._buttonLB;
  78013. },
  78014. /**
  78015. * Sets the value of the `Left` button
  78016. */
  78017. set: function (value) {
  78018. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  78019. },
  78020. enumerable: true,
  78021. configurable: true
  78022. });
  78023. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  78024. /**
  78025. * Gets the value of the `Right` button
  78026. */
  78027. get: function () {
  78028. return this._buttonRB;
  78029. },
  78030. /**
  78031. * Sets the value of the `Right` button
  78032. */
  78033. set: function (value) {
  78034. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  78035. },
  78036. enumerable: true,
  78037. configurable: true
  78038. });
  78039. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  78040. /**
  78041. * Gets the value of the Left joystick
  78042. */
  78043. get: function () {
  78044. return this._buttonLeftStick;
  78045. },
  78046. /**
  78047. * Sets the value of the Left joystick
  78048. */
  78049. set: function (value) {
  78050. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  78051. },
  78052. enumerable: true,
  78053. configurable: true
  78054. });
  78055. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  78056. /**
  78057. * Gets the value of the Right joystick
  78058. */
  78059. get: function () {
  78060. return this._buttonRightStick;
  78061. },
  78062. /**
  78063. * Sets the value of the Right joystick
  78064. */
  78065. set: function (value) {
  78066. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  78067. },
  78068. enumerable: true,
  78069. configurable: true
  78070. });
  78071. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  78072. /**
  78073. * Gets the value of D-pad up
  78074. */
  78075. get: function () {
  78076. return this._dPadUp;
  78077. },
  78078. /**
  78079. * Sets the value of D-pad up
  78080. */
  78081. set: function (value) {
  78082. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  78083. },
  78084. enumerable: true,
  78085. configurable: true
  78086. });
  78087. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  78088. /**
  78089. * Gets the value of D-pad down
  78090. */
  78091. get: function () {
  78092. return this._dPadDown;
  78093. },
  78094. /**
  78095. * Sets the value of D-pad down
  78096. */
  78097. set: function (value) {
  78098. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  78099. },
  78100. enumerable: true,
  78101. configurable: true
  78102. });
  78103. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  78104. /**
  78105. * Gets the value of D-pad left
  78106. */
  78107. get: function () {
  78108. return this._dPadLeft;
  78109. },
  78110. /**
  78111. * Sets the value of D-pad left
  78112. */
  78113. set: function (value) {
  78114. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  78115. },
  78116. enumerable: true,
  78117. configurable: true
  78118. });
  78119. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  78120. /**
  78121. * Gets the value of D-pad right
  78122. */
  78123. get: function () {
  78124. return this._dPadRight;
  78125. },
  78126. /**
  78127. * Sets the value of D-pad right
  78128. */
  78129. set: function (value) {
  78130. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  78131. },
  78132. enumerable: true,
  78133. configurable: true
  78134. });
  78135. /**
  78136. * Force the gamepad to synchronize with device values
  78137. */
  78138. Xbox360Pad.prototype.update = function () {
  78139. _super.prototype.update.call(this);
  78140. if (this._isXboxOnePad) {
  78141. this.buttonA = this.browserGamepad.buttons[0].value;
  78142. this.buttonB = this.browserGamepad.buttons[1].value;
  78143. this.buttonX = this.browserGamepad.buttons[2].value;
  78144. this.buttonY = this.browserGamepad.buttons[3].value;
  78145. this.buttonLB = this.browserGamepad.buttons[4].value;
  78146. this.buttonRB = this.browserGamepad.buttons[5].value;
  78147. this.leftTrigger = this.browserGamepad.axes[2];
  78148. this.rightTrigger = this.browserGamepad.axes[5];
  78149. this.buttonBack = this.browserGamepad.buttons[9].value;
  78150. this.buttonStart = this.browserGamepad.buttons[8].value;
  78151. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  78152. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  78153. this.dPadUp = this.browserGamepad.buttons[11].value;
  78154. this.dPadDown = this.browserGamepad.buttons[12].value;
  78155. this.dPadLeft = this.browserGamepad.buttons[13].value;
  78156. this.dPadRight = this.browserGamepad.buttons[14].value;
  78157. }
  78158. else {
  78159. this.buttonA = this.browserGamepad.buttons[0].value;
  78160. this.buttonB = this.browserGamepad.buttons[1].value;
  78161. this.buttonX = this.browserGamepad.buttons[2].value;
  78162. this.buttonY = this.browserGamepad.buttons[3].value;
  78163. this.buttonLB = this.browserGamepad.buttons[4].value;
  78164. this.buttonRB = this.browserGamepad.buttons[5].value;
  78165. this.leftTrigger = this.browserGamepad.buttons[6].value;
  78166. this.rightTrigger = this.browserGamepad.buttons[7].value;
  78167. this.buttonBack = this.browserGamepad.buttons[8].value;
  78168. this.buttonStart = this.browserGamepad.buttons[9].value;
  78169. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  78170. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  78171. this.dPadUp = this.browserGamepad.buttons[12].value;
  78172. this.dPadDown = this.browserGamepad.buttons[13].value;
  78173. this.dPadLeft = this.browserGamepad.buttons[14].value;
  78174. this.dPadRight = this.browserGamepad.buttons[15].value;
  78175. }
  78176. };
  78177. /**
  78178. * Disposes the gamepad
  78179. */
  78180. Xbox360Pad.prototype.dispose = function () {
  78181. _super.prototype.dispose.call(this);
  78182. this.onButtonDownObservable.clear();
  78183. this.onButtonUpObservable.clear();
  78184. this.onPadDownObservable.clear();
  78185. this.onPadUpObservable.clear();
  78186. };
  78187. return Xbox360Pad;
  78188. }(BABYLON.Gamepad));
  78189. BABYLON.Xbox360Pad = Xbox360Pad;
  78190. })(BABYLON || (BABYLON = {}));
  78191. //# sourceMappingURL=babylon.xboxGamepad.js.map
  78192. var BABYLON;
  78193. (function (BABYLON) {
  78194. /**
  78195. * Defines the types of pose enabled controllers that are supported
  78196. */
  78197. var PoseEnabledControllerType;
  78198. (function (PoseEnabledControllerType) {
  78199. /**
  78200. * HTC Vive
  78201. */
  78202. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  78203. /**
  78204. * Oculus Rift
  78205. */
  78206. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  78207. /**
  78208. * Windows mixed reality
  78209. */
  78210. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  78211. /**
  78212. * Samsung gear VR
  78213. */
  78214. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  78215. /**
  78216. * Google Daydream
  78217. */
  78218. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  78219. /**
  78220. * Generic
  78221. */
  78222. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  78223. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  78224. /**
  78225. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78226. */
  78227. var PoseEnabledControllerHelper = /** @class */ (function () {
  78228. function PoseEnabledControllerHelper() {
  78229. }
  78230. /**
  78231. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  78232. * @param vrGamepad the gamepad to initialized
  78233. * @returns a vr controller of the type the gamepad identified as
  78234. */
  78235. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  78236. // Oculus Touch
  78237. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  78238. return new BABYLON.OculusTouchController(vrGamepad);
  78239. }
  78240. // Windows Mixed Reality controllers
  78241. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  78242. return new BABYLON.WindowsMotionController(vrGamepad);
  78243. }
  78244. // HTC Vive
  78245. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  78246. return new BABYLON.ViveController(vrGamepad);
  78247. }
  78248. // Samsung/Oculus Gear VR or Oculus Go
  78249. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  78250. return new BABYLON.GearVRController(vrGamepad);
  78251. }
  78252. // Google Daydream
  78253. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  78254. return new BABYLON.DaydreamController(vrGamepad);
  78255. }
  78256. // Generic
  78257. else {
  78258. return new BABYLON.GenericController(vrGamepad);
  78259. }
  78260. };
  78261. return PoseEnabledControllerHelper;
  78262. }());
  78263. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  78264. /**
  78265. * Defines the PoseEnabledController object that contains state of a vr capable controller
  78266. */
  78267. var PoseEnabledController = /** @class */ (function (_super) {
  78268. __extends(PoseEnabledController, _super);
  78269. /**
  78270. * Creates a new PoseEnabledController from a gamepad
  78271. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  78272. */
  78273. function PoseEnabledController(browserGamepad) {
  78274. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  78275. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78276. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78277. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  78278. /**
  78279. * The device position in babylon space
  78280. */
  78281. _this.devicePosition = BABYLON.Vector3.Zero();
  78282. /**
  78283. * The device rotation in babylon space
  78284. */
  78285. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  78286. /**
  78287. * The scale factor of the device in babylon space
  78288. */
  78289. _this.deviceScaleFactor = 1;
  78290. // Used to convert 6dof controllers to 3dof
  78291. _this._trackPosition = true;
  78292. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78293. _this._draggedRoomRotation = 0;
  78294. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  78295. /**
  78296. * Internal, matrix used to convert room space to babylon space
  78297. * @hidden
  78298. */
  78299. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78300. /**
  78301. * Node to be used when casting a ray from the controller
  78302. * @hidden
  78303. */
  78304. _this._pointingPoseNode = null;
  78305. _this._workingMatrix = BABYLON.Matrix.Identity();
  78306. /**
  78307. * @hidden
  78308. */
  78309. _this._meshAttachedObservable = new BABYLON.Observable();
  78310. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  78311. _this.controllerType = PoseEnabledControllerType.GENERIC;
  78312. _this.position = BABYLON.Vector3.Zero();
  78313. _this.rotationQuaternion = new BABYLON.Quaternion();
  78314. _this._calculatedPosition = BABYLON.Vector3.Zero();
  78315. _this._calculatedRotation = new BABYLON.Quaternion();
  78316. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  78317. return _this;
  78318. }
  78319. /**
  78320. * @hidden
  78321. */
  78322. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  78323. if (this._trackPosition) {
  78324. this._calculatedPosition.copyFrom(fixedPosition);
  78325. this._trackPosition = false;
  78326. }
  78327. };
  78328. /**
  78329. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  78330. */
  78331. PoseEnabledController.prototype.update = function () {
  78332. _super.prototype.update.call(this);
  78333. this._updatePoseAndMesh();
  78334. };
  78335. /**
  78336. * Updates only the pose device and mesh without doing any button event checking
  78337. */
  78338. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  78339. var pose = this.browserGamepad.pose;
  78340. this.updateFromDevice(pose);
  78341. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  78342. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78343. camera._computeDevicePosition();
  78344. this._deviceToWorld.setTranslation(camera.devicePosition);
  78345. if (camera.deviceRotationQuaternion) {
  78346. var camera = camera;
  78347. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  78348. // Find the radian distance away that the headset is from the controllers rotation
  78349. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  78350. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78351. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78352. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78353. this._draggedRoomRotation += rotationAmount;
  78354. // Rotate controller around headset
  78355. var sin = Math.sin(-rotationAmount);
  78356. var cos = Math.cos(-rotationAmount);
  78357. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78358. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78359. }
  78360. }
  78361. }
  78362. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  78363. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  78364. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78365. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  78366. if (this._mesh) {
  78367. this._mesh.position.copyFrom(this.devicePosition);
  78368. if (this._mesh.rotationQuaternion) {
  78369. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  78370. }
  78371. }
  78372. };
  78373. /**
  78374. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78375. * @param poseData raw pose fromthe device
  78376. */
  78377. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  78378. if (poseData) {
  78379. this.rawPose = poseData;
  78380. if (poseData.position) {
  78381. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  78382. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  78383. this._deviceRoomPosition.z *= -1;
  78384. }
  78385. if (this._trackPosition) {
  78386. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  78387. }
  78388. this._calculatedPosition.addInPlace(this.position);
  78389. }
  78390. var pose = this.rawPose;
  78391. if (poseData.orientation && pose.orientation) {
  78392. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  78393. if (this._mesh) {
  78394. if (this._mesh.getScene().useRightHandedSystem) {
  78395. this._deviceRoomRotationQuaternion.z *= -1;
  78396. this._deviceRoomRotationQuaternion.w *= -1;
  78397. }
  78398. else {
  78399. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  78400. }
  78401. }
  78402. // if the camera is set, rotate to the camera's rotation
  78403. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  78404. }
  78405. }
  78406. };
  78407. /**
  78408. * Attaches a mesh to the controller
  78409. * @param mesh the mesh to be attached
  78410. */
  78411. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  78412. if (this._mesh) {
  78413. this._mesh.parent = null;
  78414. }
  78415. this._mesh = mesh;
  78416. if (this._poseControlledCamera) {
  78417. this._mesh.parent = this._poseControlledCamera;
  78418. }
  78419. if (!this._mesh.rotationQuaternion) {
  78420. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  78421. }
  78422. // 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
  78423. this._updatePoseAndMesh();
  78424. if (this._pointingPoseNode) {
  78425. var parents = [];
  78426. var obj = this._pointingPoseNode;
  78427. while (obj.parent) {
  78428. parents.push(obj.parent);
  78429. obj = obj.parent;
  78430. }
  78431. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  78432. }
  78433. this._meshAttachedObservable.notifyObservers(mesh);
  78434. };
  78435. /**
  78436. * Attaches the controllers mesh to a camera
  78437. * @param camera the camera the mesh should be attached to
  78438. */
  78439. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  78440. this._poseControlledCamera = camera;
  78441. if (this._mesh) {
  78442. this._mesh.parent = this._poseControlledCamera;
  78443. }
  78444. };
  78445. /**
  78446. * Disposes of the controller
  78447. */
  78448. PoseEnabledController.prototype.dispose = function () {
  78449. if (this._mesh) {
  78450. this._mesh.dispose();
  78451. }
  78452. this._mesh = null;
  78453. _super.prototype.dispose.call(this);
  78454. };
  78455. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  78456. /**
  78457. * The mesh that is attached to the controller
  78458. */
  78459. get: function () {
  78460. return this._mesh;
  78461. },
  78462. enumerable: true,
  78463. configurable: true
  78464. });
  78465. /**
  78466. * Gets the ray of the controller in the direction the controller is pointing
  78467. * @param length the length the resulting ray should be
  78468. * @returns a ray in the direction the controller is pointing
  78469. */
  78470. PoseEnabledController.prototype.getForwardRay = function (length) {
  78471. if (length === void 0) { length = 100; }
  78472. if (!this.mesh) {
  78473. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  78474. }
  78475. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  78476. var origin = m.getTranslation();
  78477. var forward = new BABYLON.Vector3(0, 0, -1);
  78478. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78479. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78480. return new BABYLON.Ray(origin, direction, length);
  78481. };
  78482. /**
  78483. * Name of the child mesh that can be used to cast a ray from the controller
  78484. */
  78485. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  78486. return PoseEnabledController;
  78487. }(BABYLON.Gamepad));
  78488. BABYLON.PoseEnabledController = PoseEnabledController;
  78489. })(BABYLON || (BABYLON = {}));
  78490. //# sourceMappingURL=babylon.poseEnabledController.js.map
  78491. var BABYLON;
  78492. (function (BABYLON) {
  78493. /**
  78494. * Defines the WebVRController object that represents controllers tracked in 3D space
  78495. */
  78496. var WebVRController = /** @class */ (function (_super) {
  78497. __extends(WebVRController, _super);
  78498. /**
  78499. * Creates a new WebVRController from a gamepad
  78500. * @param vrGamepad the gamepad that the WebVRController should be created from
  78501. */
  78502. function WebVRController(vrGamepad) {
  78503. var _this = _super.call(this, vrGamepad) || this;
  78504. // Observables
  78505. /**
  78506. * Fired when the trigger state has changed
  78507. */
  78508. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  78509. /**
  78510. * Fired when the main button state has changed
  78511. */
  78512. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  78513. /**
  78514. * Fired when the secondary button state has changed
  78515. */
  78516. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  78517. /**
  78518. * Fired when the pad state has changed
  78519. */
  78520. _this.onPadStateChangedObservable = new BABYLON.Observable();
  78521. /**
  78522. * Fired when controllers stick values have changed
  78523. */
  78524. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  78525. /**
  78526. * X and Y axis corrisponding to the controllers joystick
  78527. */
  78528. _this.pad = { x: 0, y: 0 };
  78529. // avoid GC, store state in a tmp object
  78530. _this._changes = {
  78531. pressChanged: false,
  78532. touchChanged: false,
  78533. valueChanged: false,
  78534. changed: false
  78535. };
  78536. _this._buttons = new Array(vrGamepad.buttons.length);
  78537. _this.hand = vrGamepad.hand;
  78538. return _this;
  78539. }
  78540. /**
  78541. * Fired when a controller button's state has changed
  78542. * @param callback the callback containing the button that was modified
  78543. */
  78544. WebVRController.prototype.onButtonStateChange = function (callback) {
  78545. this._onButtonStateChange = callback;
  78546. };
  78547. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  78548. /**
  78549. * The default controller model for the controller
  78550. */
  78551. get: function () {
  78552. return this._defaultModel;
  78553. },
  78554. enumerable: true,
  78555. configurable: true
  78556. });
  78557. /**
  78558. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  78559. */
  78560. WebVRController.prototype.update = function () {
  78561. _super.prototype.update.call(this);
  78562. for (var index = 0; index < this._buttons.length; index++) {
  78563. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  78564. }
  78565. ;
  78566. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  78567. this.pad.x = this.leftStick.x;
  78568. this.pad.y = this.leftStick.y;
  78569. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  78570. }
  78571. };
  78572. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  78573. if (!newState) {
  78574. newState = {
  78575. pressed: false,
  78576. touched: false,
  78577. value: 0
  78578. };
  78579. }
  78580. if (!currentState) {
  78581. this._buttons[buttonIndex] = {
  78582. pressed: newState.pressed,
  78583. touched: newState.touched,
  78584. value: newState.value
  78585. };
  78586. return;
  78587. }
  78588. this._checkChanges(newState, currentState);
  78589. if (this._changes.changed) {
  78590. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  78591. this._handleButtonChange(buttonIndex, newState, this._changes);
  78592. }
  78593. this._buttons[buttonIndex].pressed = newState.pressed;
  78594. this._buttons[buttonIndex].touched = newState.touched;
  78595. // oculus triggers are never 0, thou not touched.
  78596. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  78597. };
  78598. WebVRController.prototype._checkChanges = function (newState, currentState) {
  78599. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  78600. this._changes.touchChanged = newState.touched !== currentState.touched;
  78601. this._changes.valueChanged = newState.value !== currentState.value;
  78602. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  78603. return this._changes;
  78604. };
  78605. /**
  78606. * Disposes of th webVRCOntroller
  78607. */
  78608. WebVRController.prototype.dispose = function () {
  78609. _super.prototype.dispose.call(this);
  78610. this.onTriggerStateChangedObservable.clear();
  78611. this.onMainButtonStateChangedObservable.clear();
  78612. this.onSecondaryButtonStateChangedObservable.clear();
  78613. this.onPadStateChangedObservable.clear();
  78614. this.onPadValuesChangedObservable.clear();
  78615. };
  78616. return WebVRController;
  78617. }(BABYLON.PoseEnabledController));
  78618. BABYLON.WebVRController = WebVRController;
  78619. })(BABYLON || (BABYLON = {}));
  78620. //# sourceMappingURL=babylon.webVRController.js.map
  78621. var BABYLON;
  78622. (function (BABYLON) {
  78623. /**
  78624. * Oculus Touch Controller
  78625. */
  78626. var OculusTouchController = /** @class */ (function (_super) {
  78627. __extends(OculusTouchController, _super);
  78628. /**
  78629. * Creates a new OculusTouchController from a gamepad
  78630. * @param vrGamepad the gamepad that the controller should be created from
  78631. */
  78632. function OculusTouchController(vrGamepad) {
  78633. var _this = _super.call(this, vrGamepad) || this;
  78634. /**
  78635. * Fired when the secondary trigger on this controller is modified
  78636. */
  78637. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  78638. /**
  78639. * Fired when the thumb rest on this controller is modified
  78640. */
  78641. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  78642. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  78643. return _this;
  78644. }
  78645. /**
  78646. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78647. * @param scene scene in which to add meshes
  78648. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78649. */
  78650. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78651. var _this = this;
  78652. var meshName;
  78653. // Hand
  78654. if (this.hand === 'left') {
  78655. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  78656. }
  78657. else { // Right is the default if no hand is specified
  78658. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  78659. }
  78660. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  78661. /*
  78662. Parent Mesh name: oculus_touch_left
  78663. - body
  78664. - trigger
  78665. - thumbstick
  78666. - grip
  78667. - button_y
  78668. - button_x
  78669. - button_enter
  78670. */
  78671. _this._defaultModel = newMeshes[1];
  78672. _this.attachToMesh(_this._defaultModel);
  78673. if (meshLoaded) {
  78674. meshLoaded(_this._defaultModel);
  78675. }
  78676. });
  78677. };
  78678. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  78679. /**
  78680. * Fired when the A button on this controller is modified
  78681. */
  78682. get: function () {
  78683. if (this.hand === 'right') {
  78684. return this.onMainButtonStateChangedObservable;
  78685. }
  78686. else {
  78687. throw new Error('No A button on left hand');
  78688. }
  78689. },
  78690. enumerable: true,
  78691. configurable: true
  78692. });
  78693. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  78694. /**
  78695. * Fired when the B button on this controller is modified
  78696. */
  78697. get: function () {
  78698. if (this.hand === 'right') {
  78699. return this.onSecondaryButtonStateChangedObservable;
  78700. }
  78701. else {
  78702. throw new Error('No B button on left hand');
  78703. }
  78704. },
  78705. enumerable: true,
  78706. configurable: true
  78707. });
  78708. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  78709. /**
  78710. * Fired when the X button on this controller is modified
  78711. */
  78712. get: function () {
  78713. if (this.hand === 'left') {
  78714. return this.onMainButtonStateChangedObservable;
  78715. }
  78716. else {
  78717. throw new Error('No X button on right hand');
  78718. }
  78719. },
  78720. enumerable: true,
  78721. configurable: true
  78722. });
  78723. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  78724. /**
  78725. * Fired when the Y button on this controller is modified
  78726. */
  78727. get: function () {
  78728. if (this.hand === 'left') {
  78729. return this.onSecondaryButtonStateChangedObservable;
  78730. }
  78731. else {
  78732. throw new Error('No Y button on right hand');
  78733. }
  78734. },
  78735. enumerable: true,
  78736. configurable: true
  78737. });
  78738. /**
  78739. * Called once for each button that changed state since the last frame
  78740. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  78741. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  78742. * 2) secondary trigger (same)
  78743. * 3) A (right) X (left), touch, pressed = value
  78744. * 4) B / Y
  78745. * 5) thumb rest
  78746. * @param buttonIdx Which button index changed
  78747. * @param state New state of the button
  78748. * @param changes Which properties on the state changed since last frame
  78749. */
  78750. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78751. var notifyObject = state; //{ state: state, changes: changes };
  78752. var triggerDirection = this.hand === 'right' ? -1 : 1;
  78753. switch (buttonIdx) {
  78754. case 0:
  78755. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78756. return;
  78757. case 1: // index trigger
  78758. if (this._defaultModel) {
  78759. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  78760. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  78761. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  78762. }
  78763. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78764. return;
  78765. case 2: // secondary trigger
  78766. if (this._defaultModel) {
  78767. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  78768. }
  78769. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  78770. return;
  78771. case 3:
  78772. if (this._defaultModel) {
  78773. if (notifyObject.pressed) {
  78774. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  78775. }
  78776. else {
  78777. (this._defaultModel.getChildren()[1]).position.y = 0;
  78778. }
  78779. }
  78780. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78781. return;
  78782. case 4:
  78783. if (this._defaultModel) {
  78784. if (notifyObject.pressed) {
  78785. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78786. }
  78787. else {
  78788. (this._defaultModel.getChildren()[2]).position.y = 0;
  78789. }
  78790. }
  78791. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78792. return;
  78793. case 5:
  78794. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  78795. return;
  78796. }
  78797. };
  78798. /**
  78799. * Base Url for the controller model.
  78800. */
  78801. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  78802. /**
  78803. * File name for the left controller model.
  78804. */
  78805. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  78806. /**
  78807. * File name for the right controller model.
  78808. */
  78809. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  78810. return OculusTouchController;
  78811. }(BABYLON.WebVRController));
  78812. BABYLON.OculusTouchController = OculusTouchController;
  78813. })(BABYLON || (BABYLON = {}));
  78814. //# sourceMappingURL=babylon.oculusTouchController.js.map
  78815. var BABYLON;
  78816. (function (BABYLON) {
  78817. /**
  78818. * Vive Controller
  78819. */
  78820. var ViveController = /** @class */ (function (_super) {
  78821. __extends(ViveController, _super);
  78822. /**
  78823. * Creates a new ViveController from a gamepad
  78824. * @param vrGamepad the gamepad that the controller should be created from
  78825. */
  78826. function ViveController(vrGamepad) {
  78827. var _this = _super.call(this, vrGamepad) || this;
  78828. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  78829. _this._invertLeftStickY = true;
  78830. return _this;
  78831. }
  78832. /**
  78833. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78834. * @param scene scene in which to add meshes
  78835. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78836. */
  78837. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78838. var _this = this;
  78839. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  78840. /*
  78841. Parent Mesh name: ViveWand
  78842. - body
  78843. - r_gripper
  78844. - l_gripper
  78845. - menu_button
  78846. - system_button
  78847. - trackpad
  78848. - trigger
  78849. - LED
  78850. */
  78851. _this._defaultModel = newMeshes[1];
  78852. _this.attachToMesh(_this._defaultModel);
  78853. if (meshLoaded) {
  78854. meshLoaded(_this._defaultModel);
  78855. }
  78856. });
  78857. };
  78858. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  78859. /**
  78860. * Fired when the left button on this controller is modified
  78861. */
  78862. get: function () {
  78863. return this.onMainButtonStateChangedObservable;
  78864. },
  78865. enumerable: true,
  78866. configurable: true
  78867. });
  78868. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  78869. /**
  78870. * Fired when the right button on this controller is modified
  78871. */
  78872. get: function () {
  78873. return this.onMainButtonStateChangedObservable;
  78874. },
  78875. enumerable: true,
  78876. configurable: true
  78877. });
  78878. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  78879. /**
  78880. * Fired when the menu button on this controller is modified
  78881. */
  78882. get: function () {
  78883. return this.onSecondaryButtonStateChangedObservable;
  78884. },
  78885. enumerable: true,
  78886. configurable: true
  78887. });
  78888. /**
  78889. * Called once for each button that changed state since the last frame
  78890. * Vive mapping:
  78891. * 0: touchpad
  78892. * 1: trigger
  78893. * 2: left AND right buttons
  78894. * 3: menu button
  78895. * @param buttonIdx Which button index changed
  78896. * @param state New state of the button
  78897. * @param changes Which properties on the state changed since last frame
  78898. */
  78899. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78900. var notifyObject = state; //{ state: state, changes: changes };
  78901. switch (buttonIdx) {
  78902. case 0:
  78903. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  78904. return;
  78905. case 1: // index trigger
  78906. if (this._defaultModel) {
  78907. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  78908. }
  78909. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  78910. return;
  78911. case 2: // left AND right button
  78912. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  78913. return;
  78914. case 3:
  78915. if (this._defaultModel) {
  78916. if (notifyObject.pressed) {
  78917. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  78918. }
  78919. else {
  78920. (this._defaultModel.getChildren()[2]).position.y = 0;
  78921. }
  78922. }
  78923. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  78924. return;
  78925. }
  78926. };
  78927. /**
  78928. * Base Url for the controller model.
  78929. */
  78930. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  78931. /**
  78932. * File name for the controller model.
  78933. */
  78934. ViveController.MODEL_FILENAME = 'wand.babylon';
  78935. return ViveController;
  78936. }(BABYLON.WebVRController));
  78937. BABYLON.ViveController = ViveController;
  78938. })(BABYLON || (BABYLON = {}));
  78939. //# sourceMappingURL=babylon.viveController.js.map
  78940. var BABYLON;
  78941. (function (BABYLON) {
  78942. /**
  78943. * Generic Controller
  78944. */
  78945. var GenericController = /** @class */ (function (_super) {
  78946. __extends(GenericController, _super);
  78947. /**
  78948. * Creates a new GenericController from a gamepad
  78949. * @param vrGamepad the gamepad that the controller should be created from
  78950. */
  78951. function GenericController(vrGamepad) {
  78952. return _super.call(this, vrGamepad) || this;
  78953. }
  78954. /**
  78955. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78956. * @param scene scene in which to add meshes
  78957. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78958. */
  78959. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78960. var _this = this;
  78961. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78962. _this._defaultModel = newMeshes[1];
  78963. _this.attachToMesh(_this._defaultModel);
  78964. if (meshLoaded) {
  78965. meshLoaded(_this._defaultModel);
  78966. }
  78967. });
  78968. };
  78969. /**
  78970. * Called once for each button that changed state since the last frame
  78971. * @param buttonIdx Which button index changed
  78972. * @param state New state of the button
  78973. * @param changes Which properties on the state changed since last frame
  78974. */
  78975. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78976. console.log("Button id: " + buttonIdx + "state: ");
  78977. console.dir(state);
  78978. };
  78979. /**
  78980. * Base Url for the controller model.
  78981. */
  78982. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78983. /**
  78984. * File name for the controller model.
  78985. */
  78986. GenericController.MODEL_FILENAME = 'generic.babylon';
  78987. return GenericController;
  78988. }(BABYLON.WebVRController));
  78989. BABYLON.GenericController = GenericController;
  78990. })(BABYLON || (BABYLON = {}));
  78991. //# sourceMappingURL=babylon.genericController.js.map
  78992. var BABYLON;
  78993. (function (BABYLON) {
  78994. /**
  78995. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78996. */
  78997. var LoadedMeshInfo = /** @class */ (function () {
  78998. function LoadedMeshInfo() {
  78999. /**
  79000. * Map of the button meshes contained in the controller
  79001. */
  79002. this.buttonMeshes = {};
  79003. /**
  79004. * Map of the axis meshes contained in the controller
  79005. */
  79006. this.axisMeshes = {};
  79007. }
  79008. return LoadedMeshInfo;
  79009. }());
  79010. /**
  79011. * Defines the WindowsMotionController object that the state of the windows motion controller
  79012. */
  79013. var WindowsMotionController = /** @class */ (function (_super) {
  79014. __extends(WindowsMotionController, _super);
  79015. /**
  79016. * Creates a new WindowsMotionController from a gamepad
  79017. * @param vrGamepad the gamepad that the controller should be created from
  79018. */
  79019. function WindowsMotionController(vrGamepad) {
  79020. var _this = _super.call(this, vrGamepad) || this;
  79021. _this._mapping = {
  79022. // Semantic button names
  79023. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  79024. // A mapping of the button name to glTF model node name
  79025. // that should be transformed by button value.
  79026. buttonMeshNames: {
  79027. 'trigger': 'SELECT',
  79028. 'menu': 'MENU',
  79029. 'grip': 'GRASP',
  79030. 'thumbstick': 'THUMBSTICK_PRESS',
  79031. 'trackpad': 'TOUCHPAD_PRESS'
  79032. },
  79033. // This mapping is used to translate from the Motion Controller to Babylon semantics
  79034. buttonObservableNames: {
  79035. 'trigger': 'onTriggerStateChangedObservable',
  79036. 'menu': 'onSecondaryButtonStateChangedObservable',
  79037. 'grip': 'onMainButtonStateChangedObservable',
  79038. 'thumbstick': 'onPadStateChangedObservable',
  79039. 'trackpad': 'onTrackpadChangedObservable'
  79040. },
  79041. // A mapping of the axis name to glTF model node name
  79042. // that should be transformed by axis value.
  79043. // This array mirrors the browserGamepad.axes array, such that
  79044. // the mesh corresponding to axis 0 is in this array index 0.
  79045. axisMeshNames: [
  79046. 'THUMBSTICK_X',
  79047. 'THUMBSTICK_Y',
  79048. 'TOUCHPAD_TOUCH_X',
  79049. 'TOUCHPAD_TOUCH_Y'
  79050. ],
  79051. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  79052. };
  79053. /**
  79054. * Fired when the trackpad on this controller is clicked
  79055. */
  79056. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  79057. /**
  79058. * Fired when the trackpad on this controller is modified
  79059. */
  79060. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  79061. /**
  79062. * The current x and y values of this controller's trackpad
  79063. */
  79064. _this.trackpad = { x: 0, y: 0 };
  79065. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  79066. _this._loadedMeshInfo = null;
  79067. return _this;
  79068. }
  79069. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  79070. /**
  79071. * Fired when the trigger on this controller is modified
  79072. */
  79073. get: function () {
  79074. return this.onTriggerStateChangedObservable;
  79075. },
  79076. enumerable: true,
  79077. configurable: true
  79078. });
  79079. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  79080. /**
  79081. * Fired when the menu button on this controller is modified
  79082. */
  79083. get: function () {
  79084. return this.onSecondaryButtonStateChangedObservable;
  79085. },
  79086. enumerable: true,
  79087. configurable: true
  79088. });
  79089. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  79090. /**
  79091. * Fired when the grip button on this controller is modified
  79092. */
  79093. get: function () {
  79094. return this.onMainButtonStateChangedObservable;
  79095. },
  79096. enumerable: true,
  79097. configurable: true
  79098. });
  79099. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  79100. /**
  79101. * Fired when the thumbstick button on this controller is modified
  79102. */
  79103. get: function () {
  79104. return this.onPadStateChangedObservable;
  79105. },
  79106. enumerable: true,
  79107. configurable: true
  79108. });
  79109. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  79110. /**
  79111. * Fired when the touchpad button on this controller is modified
  79112. */
  79113. get: function () {
  79114. return this.onTrackpadChangedObservable;
  79115. },
  79116. enumerable: true,
  79117. configurable: true
  79118. });
  79119. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  79120. /**
  79121. * Fired when the touchpad values on this controller are modified
  79122. */
  79123. get: function () {
  79124. return this.onTrackpadValuesChangedObservable;
  79125. },
  79126. enumerable: true,
  79127. configurable: true
  79128. });
  79129. WindowsMotionController.prototype._updateTrackpad = function () {
  79130. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  79131. this.trackpad.x = this.browserGamepad["axes"][2];
  79132. this.trackpad.y = this.browserGamepad["axes"][3];
  79133. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  79134. }
  79135. };
  79136. /**
  79137. * Called once per frame by the engine.
  79138. */
  79139. WindowsMotionController.prototype.update = function () {
  79140. _super.prototype.update.call(this);
  79141. if (this.browserGamepad.axes) {
  79142. this._updateTrackpad();
  79143. // Only need to animate axes if there is a loaded mesh
  79144. if (this._loadedMeshInfo) {
  79145. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  79146. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  79147. }
  79148. }
  79149. }
  79150. };
  79151. /**
  79152. * Called once for each button that changed state since the last frame
  79153. * @param buttonIdx Which button index changed
  79154. * @param state New state of the button
  79155. * @param changes Which properties on the state changed since last frame
  79156. */
  79157. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79158. var buttonName = this._mapping.buttons[buttonIdx];
  79159. if (!buttonName) {
  79160. return;
  79161. }
  79162. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  79163. this._updateTrackpad();
  79164. // Only emit events for buttons that we know how to map from index to name
  79165. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  79166. if (observable) {
  79167. observable.notifyObservers(state);
  79168. }
  79169. this._lerpButtonTransform(buttonName, state.value);
  79170. };
  79171. /**
  79172. * Moves the buttons on the controller mesh based on their current state
  79173. * @param buttonName the name of the button to move
  79174. * @param buttonValue the value of the button which determines the buttons new position
  79175. */
  79176. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  79177. // If there is no loaded mesh, there is nothing to transform.
  79178. if (!this._loadedMeshInfo) {
  79179. return;
  79180. }
  79181. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  79182. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79183. return;
  79184. }
  79185. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  79186. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  79187. };
  79188. /**
  79189. * Moves the axis on the controller mesh based on its current state
  79190. * @param axis the index of the axis
  79191. * @param axisValue the value of the axis which determines the meshes new position
  79192. * @hidden
  79193. */
  79194. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  79195. if (!this._loadedMeshInfo) {
  79196. return;
  79197. }
  79198. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  79199. if (!meshInfo) {
  79200. return;
  79201. }
  79202. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  79203. return;
  79204. }
  79205. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  79206. var lerpValue = axisValue * 0.5 + 0.5;
  79207. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  79208. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  79209. };
  79210. /**
  79211. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79212. * @param scene scene in which to add meshes
  79213. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79214. */
  79215. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  79216. var _this = this;
  79217. if (forceDefault === void 0) { forceDefault = false; }
  79218. var path;
  79219. var filename;
  79220. // Checking if GLB loader is present
  79221. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  79222. // Determine the device specific folder based on the ID suffix
  79223. var device = 'default';
  79224. if (this.id && !forceDefault) {
  79225. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  79226. device = ((match && match[0]) || device);
  79227. }
  79228. // Hand
  79229. if (this.hand === 'left') {
  79230. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  79231. }
  79232. else { // Right is the default if no hand is specified
  79233. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  79234. }
  79235. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  79236. }
  79237. else {
  79238. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  79239. path = BABYLON.GenericController.MODEL_BASE_URL;
  79240. filename = BABYLON.GenericController.MODEL_FILENAME;
  79241. }
  79242. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  79243. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  79244. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  79245. if (!_this._loadedMeshInfo) {
  79246. return;
  79247. }
  79248. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  79249. _this.attachToMesh(_this._defaultModel);
  79250. if (meshLoaded) {
  79251. meshLoaded(_this._defaultModel);
  79252. }
  79253. }, null, function (scene, message) {
  79254. BABYLON.Tools.Log(message);
  79255. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  79256. if (!forceDefault) {
  79257. _this.initControllerMesh(scene, meshLoaded, true);
  79258. }
  79259. });
  79260. };
  79261. /**
  79262. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  79263. * can be transformed by button presses and axes values, based on this._mapping.
  79264. *
  79265. * @param scene scene in which the meshes exist
  79266. * @param meshes list of meshes that make up the controller model to process
  79267. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  79268. */
  79269. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  79270. var loadedMeshInfo = null;
  79271. // Create a new mesh to contain the glTF hierarchy
  79272. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  79273. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  79274. var childMesh = null;
  79275. for (var i = 0; i < meshes.length; i++) {
  79276. var mesh = meshes[i];
  79277. if (!mesh.parent) {
  79278. // Exclude controller meshes from picking results
  79279. mesh.isPickable = false;
  79280. // Handle root node, attach to the new parentMesh
  79281. childMesh = mesh;
  79282. break;
  79283. }
  79284. }
  79285. if (childMesh) {
  79286. childMesh.setParent(parentMesh);
  79287. // Create our mesh info. Note that this method will always return non-null.
  79288. loadedMeshInfo = this.createMeshInfo(parentMesh);
  79289. }
  79290. else {
  79291. BABYLON.Tools.Warn('Could not find root node in model file.');
  79292. }
  79293. return loadedMeshInfo;
  79294. };
  79295. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  79296. var loadedMeshInfo = new LoadedMeshInfo();
  79297. var i;
  79298. loadedMeshInfo.rootNode = rootNode;
  79299. // Reset the caches
  79300. loadedMeshInfo.buttonMeshes = {};
  79301. loadedMeshInfo.axisMeshes = {};
  79302. // Button Meshes
  79303. for (i = 0; i < this._mapping.buttons.length; i++) {
  79304. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  79305. if (!buttonMeshName) {
  79306. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  79307. continue;
  79308. }
  79309. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  79310. if (!buttonMesh) {
  79311. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  79312. continue;
  79313. }
  79314. var buttonMeshInfo = {
  79315. index: i,
  79316. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  79317. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  79318. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  79319. };
  79320. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  79321. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  79322. }
  79323. else {
  79324. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  79325. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  79326. '(VALUE: ' + !!buttonMeshInfo.value +
  79327. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  79328. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  79329. ')');
  79330. }
  79331. }
  79332. // Axis Meshes
  79333. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  79334. var axisMeshName = this._mapping.axisMeshNames[i];
  79335. if (!axisMeshName) {
  79336. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  79337. continue;
  79338. }
  79339. var axisMesh = getChildByName(rootNode, axisMeshName);
  79340. if (!axisMesh) {
  79341. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  79342. continue;
  79343. }
  79344. var axisMeshInfo = {
  79345. index: i,
  79346. value: getImmediateChildByName(axisMesh, 'VALUE'),
  79347. min: getImmediateChildByName(axisMesh, 'MIN'),
  79348. max: getImmediateChildByName(axisMesh, 'MAX')
  79349. };
  79350. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  79351. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  79352. }
  79353. else {
  79354. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  79355. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  79356. '(VALUE: ' + !!axisMeshInfo.value +
  79357. ', MIN: ' + !!axisMeshInfo.min +
  79358. ', MAX:' + !!axisMeshInfo.max +
  79359. ')');
  79360. }
  79361. }
  79362. // Pointing Ray
  79363. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  79364. if (!loadedMeshInfo.pointingPoseNode) {
  79365. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  79366. }
  79367. else {
  79368. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  79369. }
  79370. return loadedMeshInfo;
  79371. // Look through all children recursively. This will return null if no mesh exists with the given name.
  79372. function getChildByName(node, name) {
  79373. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  79374. }
  79375. // Look through only immediate children. This will return null if no mesh exists with the given name.
  79376. function getImmediateChildByName(node, name) {
  79377. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  79378. }
  79379. };
  79380. /**
  79381. * Gets the ray of the controller in the direction the controller is pointing
  79382. * @param length the length the resulting ray should be
  79383. * @returns a ray in the direction the controller is pointing
  79384. */
  79385. WindowsMotionController.prototype.getForwardRay = function (length) {
  79386. if (length === void 0) { length = 100; }
  79387. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  79388. return _super.prototype.getForwardRay.call(this, length);
  79389. }
  79390. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  79391. var origin = m.getTranslation();
  79392. var forward = new BABYLON.Vector3(0, 0, -1);
  79393. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  79394. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  79395. return new BABYLON.Ray(origin, direction, length);
  79396. };
  79397. /**
  79398. * Disposes of the controller
  79399. */
  79400. WindowsMotionController.prototype.dispose = function () {
  79401. _super.prototype.dispose.call(this);
  79402. this.onTrackpadChangedObservable.clear();
  79403. };
  79404. /**
  79405. * The base url used to load the left and right controller models
  79406. */
  79407. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  79408. /**
  79409. * The name of the left controller model file
  79410. */
  79411. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  79412. /**
  79413. * The name of the right controller model file
  79414. */
  79415. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  79416. /**
  79417. * The controller name prefix for this controller type
  79418. */
  79419. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  79420. /**
  79421. * The controller id pattern for this controller type
  79422. */
  79423. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  79424. return WindowsMotionController;
  79425. }(BABYLON.WebVRController));
  79426. BABYLON.WindowsMotionController = WindowsMotionController;
  79427. })(BABYLON || (BABYLON = {}));
  79428. //# sourceMappingURL=babylon.windowsMotionController.js.map
  79429. var BABYLON;
  79430. (function (BABYLON) {
  79431. /**
  79432. * Gear VR Controller
  79433. */
  79434. var GearVRController = /** @class */ (function (_super) {
  79435. __extends(GearVRController, _super);
  79436. /**
  79437. * Creates a new GearVRController from a gamepad
  79438. * @param vrGamepad the gamepad that the controller should be created from
  79439. */
  79440. function GearVRController(vrGamepad) {
  79441. var _this = _super.call(this, vrGamepad) || this;
  79442. _this._buttonIndexToObservableNameMap = [
  79443. 'onTrackpadChangedObservable',
  79444. 'onTriggerStateChangedObservable' // Trigger
  79445. ];
  79446. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  79447. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  79448. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  79449. _this._disableTrackPosition(_this._calculatedPosition);
  79450. return _this;
  79451. }
  79452. /**
  79453. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79454. * @param scene scene in which to add meshes
  79455. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79456. */
  79457. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79458. var _this = this;
  79459. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  79460. // Offset the controller so it will rotate around the users wrist
  79461. var mesh = new BABYLON.Mesh("", scene);
  79462. newMeshes[1].parent = mesh;
  79463. newMeshes[1].position.z = -0.15;
  79464. _this._defaultModel = mesh;
  79465. _this.attachToMesh(_this._defaultModel);
  79466. if (meshLoaded) {
  79467. meshLoaded(_this._defaultModel);
  79468. }
  79469. });
  79470. };
  79471. /**
  79472. * Called once for each button that changed state since the last frame
  79473. * @param buttonIdx Which button index changed
  79474. * @param state New state of the button
  79475. * @param changes Which properties on the state changed since last frame
  79476. */
  79477. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79478. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  79479. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  79480. // Only emit events for buttons that we know how to map from index to observable
  79481. var observable = this[observableName];
  79482. if (observable) {
  79483. observable.notifyObservers(state);
  79484. }
  79485. }
  79486. };
  79487. /**
  79488. * Base Url for the controller model.
  79489. */
  79490. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79491. /**
  79492. * File name for the controller model.
  79493. */
  79494. GearVRController.MODEL_FILENAME = 'generic.babylon';
  79495. /**
  79496. * Gamepad Id prefix used to identify this controller.
  79497. */
  79498. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  79499. return GearVRController;
  79500. }(BABYLON.WebVRController));
  79501. BABYLON.GearVRController = GearVRController;
  79502. })(BABYLON || (BABYLON = {}));
  79503. //# sourceMappingURL=babylon.gearVRController.js.map
  79504. var BABYLON;
  79505. (function (BABYLON) {
  79506. /**
  79507. * Google Daydream controller
  79508. */
  79509. var DaydreamController = /** @class */ (function (_super) {
  79510. __extends(DaydreamController, _super);
  79511. /**
  79512. * Creates a new DaydreamController from a gamepad
  79513. * @param vrGamepad the gamepad that the controller should be created from
  79514. */
  79515. function DaydreamController(vrGamepad) {
  79516. var _this = _super.call(this, vrGamepad) || this;
  79517. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  79518. return _this;
  79519. }
  79520. /**
  79521. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  79522. * @param scene scene in which to add meshes
  79523. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  79524. */
  79525. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  79526. var _this = this;
  79527. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  79528. _this._defaultModel = newMeshes[1];
  79529. _this.attachToMesh(_this._defaultModel);
  79530. if (meshLoaded) {
  79531. meshLoaded(_this._defaultModel);
  79532. }
  79533. });
  79534. };
  79535. /**
  79536. * Called once for each button that changed state since the last frame
  79537. * @param buttonIdx Which button index changed
  79538. * @param state New state of the button
  79539. * @param changes Which properties on the state changed since last frame
  79540. */
  79541. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  79542. // Daydream controller only has 1 GamepadButton (on the trackpad).
  79543. if (buttonIdx === 0) {
  79544. var observable = this.onTriggerStateChangedObservable;
  79545. if (observable) {
  79546. observable.notifyObservers(state);
  79547. }
  79548. }
  79549. else {
  79550. // If the app or home buttons are ever made available
  79551. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  79552. }
  79553. };
  79554. /**
  79555. * Base Url for the controller model.
  79556. */
  79557. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  79558. /**
  79559. * File name for the controller model.
  79560. */
  79561. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  79562. /**
  79563. * Gamepad Id prefix used to identify Daydream Controller.
  79564. */
  79565. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  79566. return DaydreamController;
  79567. }(BABYLON.WebVRController));
  79568. BABYLON.DaydreamController = DaydreamController;
  79569. })(BABYLON || (BABYLON = {}));
  79570. //# sourceMappingURL=babylon.daydreamController.js.map
  79571. var BABYLON;
  79572. (function (BABYLON) {
  79573. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  79574. get: function () {
  79575. if (!this._gamepadManager) {
  79576. this._gamepadManager = new BABYLON.GamepadManager(this);
  79577. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  79578. if (!component) {
  79579. component = new GamepadSystemSceneComponent(this);
  79580. this._addComponent(component);
  79581. }
  79582. }
  79583. return this._gamepadManager;
  79584. },
  79585. enumerable: true,
  79586. configurable: true
  79587. });
  79588. /**
  79589. * Adds a gamepad to the free camera inputs manager
  79590. */
  79591. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  79592. this.add(new BABYLON.FreeCameraGamepadInput());
  79593. return this;
  79594. };
  79595. /**
  79596. * Adds a gamepad to the arc rotate camera inputs manager
  79597. */
  79598. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  79599. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  79600. return this;
  79601. };
  79602. /**
  79603. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  79604. */
  79605. var GamepadSystemSceneComponent = /** @class */ (function () {
  79606. /**
  79607. * Creates a new instance of the component for the given scene
  79608. * @param scene Defines the scene to register the component in
  79609. */
  79610. function GamepadSystemSceneComponent(scene) {
  79611. /**
  79612. * The component name helpfull to identify the component in the list of scene components.
  79613. */
  79614. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  79615. this.scene = scene;
  79616. }
  79617. /**
  79618. * Registers the component in a given scene
  79619. */
  79620. GamepadSystemSceneComponent.prototype.register = function () {
  79621. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  79622. };
  79623. /**
  79624. * Rebuilds the elements related to this component in case of
  79625. * context lost for instance.
  79626. */
  79627. GamepadSystemSceneComponent.prototype.rebuild = function () {
  79628. // Nothing to do for gamepads
  79629. };
  79630. /**
  79631. * Disposes the component and the associated ressources
  79632. */
  79633. GamepadSystemSceneComponent.prototype.dispose = function () {
  79634. var gamepadManager = this.scene._gamepadManager;
  79635. if (gamepadManager) {
  79636. gamepadManager.dispose();
  79637. this.scene._gamepadManager = null;
  79638. }
  79639. };
  79640. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  79641. var gamepadManager = this.scene._gamepadManager;
  79642. if (gamepadManager && gamepadManager._isMonitoring) {
  79643. gamepadManager._checkGamepadsStatus();
  79644. }
  79645. };
  79646. return GamepadSystemSceneComponent;
  79647. }());
  79648. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  79649. })(BABYLON || (BABYLON = {}));
  79650. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  79651. var BABYLON;
  79652. (function (BABYLON) {
  79653. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  79654. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  79655. });
  79656. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  79657. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  79658. });
  79659. /**
  79660. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  79661. * an arc rotate version arcFollowCamera are available.
  79662. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79663. */
  79664. var FollowCamera = /** @class */ (function (_super) {
  79665. __extends(FollowCamera, _super);
  79666. /**
  79667. * Instantiates the follow camera.
  79668. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79669. * @param name Define the name of the camera in the scene
  79670. * @param position Define the position of the camera
  79671. * @param scene Define the scene the camera belong to
  79672. * @param lockedTarget Define the target of the camera
  79673. */
  79674. function FollowCamera(name, position, scene, lockedTarget) {
  79675. if (lockedTarget === void 0) { lockedTarget = null; }
  79676. var _this = _super.call(this, name, position, scene) || this;
  79677. /**
  79678. * Distance the follow camera should follow an object at
  79679. */
  79680. _this.radius = 12;
  79681. /**
  79682. * Define a rotation offset between the camera and the object it follows
  79683. */
  79684. _this.rotationOffset = 0;
  79685. /**
  79686. * Define a height offset between the camera and the object it follows.
  79687. * It can help following an object from the top (like a car chaing a plane)
  79688. */
  79689. _this.heightOffset = 4;
  79690. /**
  79691. * Define how fast the camera can accelerate to follow it s target.
  79692. */
  79693. _this.cameraAcceleration = 0.05;
  79694. /**
  79695. * Define the speed limit of the camera following an object.
  79696. */
  79697. _this.maxCameraSpeed = 20;
  79698. _this.lockedTarget = lockedTarget;
  79699. return _this;
  79700. }
  79701. FollowCamera.prototype._follow = function (cameraTarget) {
  79702. if (!cameraTarget)
  79703. return;
  79704. var yRotation;
  79705. if (cameraTarget.rotationQuaternion) {
  79706. var rotMatrix = new BABYLON.Matrix();
  79707. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  79708. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  79709. }
  79710. else {
  79711. yRotation = cameraTarget.rotation.y;
  79712. }
  79713. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  79714. var targetPosition = cameraTarget.getAbsolutePosition();
  79715. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  79716. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  79717. var dx = targetX - this.position.x;
  79718. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  79719. var dz = (targetZ) - this.position.z;
  79720. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  79721. var vy = dy * this.cameraAcceleration;
  79722. var vz = dz * this.cameraAcceleration * 2;
  79723. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  79724. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79725. }
  79726. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  79727. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79728. }
  79729. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  79730. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  79731. }
  79732. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  79733. this.setTarget(targetPosition);
  79734. };
  79735. /** @hidden */
  79736. FollowCamera.prototype._checkInputs = function () {
  79737. _super.prototype._checkInputs.call(this);
  79738. if (this.lockedTarget) {
  79739. this._follow(this.lockedTarget);
  79740. }
  79741. };
  79742. /**
  79743. * Gets the camera class name.
  79744. * @returns the class name
  79745. */
  79746. FollowCamera.prototype.getClassName = function () {
  79747. return "FollowCamera";
  79748. };
  79749. __decorate([
  79750. BABYLON.serialize()
  79751. ], FollowCamera.prototype, "radius", void 0);
  79752. __decorate([
  79753. BABYLON.serialize()
  79754. ], FollowCamera.prototype, "rotationOffset", void 0);
  79755. __decorate([
  79756. BABYLON.serialize()
  79757. ], FollowCamera.prototype, "heightOffset", void 0);
  79758. __decorate([
  79759. BABYLON.serialize()
  79760. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  79761. __decorate([
  79762. BABYLON.serialize()
  79763. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  79764. __decorate([
  79765. BABYLON.serializeAsMeshReference("lockedTargetId")
  79766. ], FollowCamera.prototype, "lockedTarget", void 0);
  79767. return FollowCamera;
  79768. }(BABYLON.TargetCamera));
  79769. BABYLON.FollowCamera = FollowCamera;
  79770. /**
  79771. * Arc Rotate version of the follow camera.
  79772. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  79773. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79774. */
  79775. var ArcFollowCamera = /** @class */ (function (_super) {
  79776. __extends(ArcFollowCamera, _super);
  79777. /**
  79778. * Instantiates a new ArcFollowCamera
  79779. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  79780. * @param name Define the name of the camera
  79781. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  79782. * @param beta Define the rotation angle of the camera around the elevation axis
  79783. * @param radius Define the radius of the camera from its target point
  79784. * @param target Define the target of the camera
  79785. * @param scene Define the scene the camera belongs to
  79786. */
  79787. function ArcFollowCamera(name,
  79788. /** The longitudinal angle of the camera */
  79789. alpha,
  79790. /** The latitudinal angle of the camera */
  79791. beta,
  79792. /** The radius of the camera from its target */
  79793. radius,
  79794. /** Define the camera target (the messh it should follow) */
  79795. target, scene) {
  79796. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  79797. _this.alpha = alpha;
  79798. _this.beta = beta;
  79799. _this.radius = radius;
  79800. _this.target = target;
  79801. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  79802. _this._follow();
  79803. return _this;
  79804. }
  79805. ArcFollowCamera.prototype._follow = function () {
  79806. if (!this.target) {
  79807. return;
  79808. }
  79809. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  79810. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  79811. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  79812. var targetPosition = this.target.getAbsolutePosition();
  79813. this.position = targetPosition.add(this._cartesianCoordinates);
  79814. this.setTarget(targetPosition);
  79815. };
  79816. /** @hidden */
  79817. ArcFollowCamera.prototype._checkInputs = function () {
  79818. _super.prototype._checkInputs.call(this);
  79819. this._follow();
  79820. };
  79821. /**
  79822. * Returns the class name of the object.
  79823. * It is mostly used internally for serialization purposes.
  79824. */
  79825. ArcFollowCamera.prototype.getClassName = function () {
  79826. return "ArcFollowCamera";
  79827. };
  79828. return ArcFollowCamera;
  79829. }(BABYLON.TargetCamera));
  79830. BABYLON.ArcFollowCamera = ArcFollowCamera;
  79831. })(BABYLON || (BABYLON = {}));
  79832. //# sourceMappingURL=babylon.followCamera.js.map
  79833. var BABYLON;
  79834. (function (BABYLON) {
  79835. /**
  79836. * 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,
  79837. * which still works and will still be found in many Playgrounds.
  79838. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79839. */
  79840. var UniversalCamera = /** @class */ (function (_super) {
  79841. __extends(UniversalCamera, _super);
  79842. /**
  79843. * 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,
  79844. * which still works and will still be found in many Playgrounds.
  79845. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79846. * @param name Define the name of the camera in the scene
  79847. * @param position Define the start position of the camera in the scene
  79848. * @param scene Define the scene the camera belongs to
  79849. */
  79850. function UniversalCamera(name, position, scene) {
  79851. var _this = _super.call(this, name, position, scene) || this;
  79852. _this.inputs.addGamepad();
  79853. return _this;
  79854. }
  79855. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  79856. /**
  79857. * Defines the gamepad rotation sensiblity.
  79858. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79859. */
  79860. get: function () {
  79861. var gamepad = this.inputs.attached["gamepad"];
  79862. if (gamepad)
  79863. return gamepad.gamepadAngularSensibility;
  79864. return 0;
  79865. },
  79866. set: function (value) {
  79867. var gamepad = this.inputs.attached["gamepad"];
  79868. if (gamepad)
  79869. gamepad.gamepadAngularSensibility = value;
  79870. },
  79871. enumerable: true,
  79872. configurable: true
  79873. });
  79874. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  79875. /**
  79876. * Defines the gamepad move sensiblity.
  79877. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79878. */
  79879. get: function () {
  79880. var gamepad = this.inputs.attached["gamepad"];
  79881. if (gamepad)
  79882. return gamepad.gamepadMoveSensibility;
  79883. return 0;
  79884. },
  79885. set: function (value) {
  79886. var gamepad = this.inputs.attached["gamepad"];
  79887. if (gamepad)
  79888. gamepad.gamepadMoveSensibility = value;
  79889. },
  79890. enumerable: true,
  79891. configurable: true
  79892. });
  79893. /**
  79894. * Gets the current object class name.
  79895. * @return the class name
  79896. */
  79897. UniversalCamera.prototype.getClassName = function () {
  79898. return "UniversalCamera";
  79899. };
  79900. return UniversalCamera;
  79901. }(BABYLON.TouchCamera));
  79902. BABYLON.UniversalCamera = UniversalCamera;
  79903. })(BABYLON || (BABYLON = {}));
  79904. //# sourceMappingURL=babylon.universalCamera.js.map
  79905. var BABYLON;
  79906. (function (BABYLON) {
  79907. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  79908. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  79909. });
  79910. /**
  79911. * This represents a FPS type of camera. This is only here for back compat purpose.
  79912. * Please use the UniversalCamera instead as both are identical.
  79913. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79914. */
  79915. var GamepadCamera = /** @class */ (function (_super) {
  79916. __extends(GamepadCamera, _super);
  79917. /**
  79918. * Instantiates a new Gamepad Camera
  79919. * This represents a FPS type of camera. This is only here for back compat purpose.
  79920. * Please use the UniversalCamera instead as both are identical.
  79921. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  79922. * @param name Define the name of the camera in the scene
  79923. * @param position Define the start position of the camera in the scene
  79924. * @param scene Define the scene the camera belongs to
  79925. */
  79926. function GamepadCamera(name, position, scene) {
  79927. return _super.call(this, name, position, scene) || this;
  79928. }
  79929. /**
  79930. * Gets the current object class name.
  79931. * @return the class name
  79932. */
  79933. GamepadCamera.prototype.getClassName = function () {
  79934. return "GamepadCamera";
  79935. };
  79936. return GamepadCamera;
  79937. }(BABYLON.UniversalCamera));
  79938. BABYLON.GamepadCamera = GamepadCamera;
  79939. })(BABYLON || (BABYLON = {}));
  79940. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79941. var BABYLON;
  79942. (function (BABYLON) {
  79943. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79944. function PostProcessRenderPipelineManager() {
  79945. this._renderPipelines = {};
  79946. }
  79947. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79948. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79949. };
  79950. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79951. if (unique === void 0) { unique = false; }
  79952. var renderPipeline = this._renderPipelines[renderPipelineName];
  79953. if (!renderPipeline) {
  79954. return;
  79955. }
  79956. renderPipeline._attachCameras(cameras, unique);
  79957. };
  79958. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79959. var renderPipeline = this._renderPipelines[renderPipelineName];
  79960. if (!renderPipeline) {
  79961. return;
  79962. }
  79963. renderPipeline._detachCameras(cameras);
  79964. };
  79965. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79966. var renderPipeline = this._renderPipelines[renderPipelineName];
  79967. if (!renderPipeline) {
  79968. return;
  79969. }
  79970. renderPipeline._enableEffect(renderEffectName, cameras);
  79971. };
  79972. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79973. var renderPipeline = this._renderPipelines[renderPipelineName];
  79974. if (!renderPipeline) {
  79975. return;
  79976. }
  79977. renderPipeline._disableEffect(renderEffectName, cameras);
  79978. };
  79979. PostProcessRenderPipelineManager.prototype.update = function () {
  79980. for (var renderPipelineName in this._renderPipelines) {
  79981. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79982. var pipeline = this._renderPipelines[renderPipelineName];
  79983. if (!pipeline.isSupported) {
  79984. pipeline.dispose();
  79985. delete this._renderPipelines[renderPipelineName];
  79986. }
  79987. else {
  79988. pipeline._update();
  79989. }
  79990. }
  79991. }
  79992. };
  79993. /** @hidden */
  79994. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79995. for (var renderPipelineName in this._renderPipelines) {
  79996. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79997. var pipeline = this._renderPipelines[renderPipelineName];
  79998. pipeline._rebuild();
  79999. }
  80000. }
  80001. };
  80002. PostProcessRenderPipelineManager.prototype.dispose = function () {
  80003. for (var renderPipelineName in this._renderPipelines) {
  80004. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  80005. var pipeline = this._renderPipelines[renderPipelineName];
  80006. pipeline.dispose();
  80007. }
  80008. }
  80009. };
  80010. return PostProcessRenderPipelineManager;
  80011. }());
  80012. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  80013. })(BABYLON || (BABYLON = {}));
  80014. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  80015. var BABYLON;
  80016. (function (BABYLON) {
  80017. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  80018. get: function () {
  80019. if (!this._postProcessRenderPipelineManager) {
  80020. // Register the G Buffer component to the scene.
  80021. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  80022. if (!component) {
  80023. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  80024. this._addComponent(component);
  80025. }
  80026. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  80027. }
  80028. return this._postProcessRenderPipelineManager;
  80029. },
  80030. enumerable: true,
  80031. configurable: true
  80032. });
  80033. /**
  80034. * Defines the Render Pipeline scene component responsible to rendering pipelines
  80035. */
  80036. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  80037. /**
  80038. * Creates a new instance of the component for the given scene
  80039. * @param scene Defines the scene to register the component in
  80040. */
  80041. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  80042. /**
  80043. * The component name helpfull to identify the component in the list of scene components.
  80044. */
  80045. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  80046. this.scene = scene;
  80047. }
  80048. /**
  80049. * Registers the component in a given scene
  80050. */
  80051. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  80052. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  80053. };
  80054. /**
  80055. * Rebuilds the elements related to this component in case of
  80056. * context lost for instance.
  80057. */
  80058. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  80059. if (this.scene._postProcessRenderPipelineManager) {
  80060. this.scene._postProcessRenderPipelineManager._rebuild();
  80061. }
  80062. };
  80063. /**
  80064. * Disposes the component and the associated ressources
  80065. */
  80066. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  80067. if (this.scene._postProcessRenderPipelineManager) {
  80068. this.scene._postProcessRenderPipelineManager.dispose();
  80069. }
  80070. };
  80071. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80072. if (this.scene._postProcessRenderPipelineManager) {
  80073. this.scene._postProcessRenderPipelineManager.update();
  80074. }
  80075. };
  80076. return PostProcessRenderPipelineManagerSceneComponent;
  80077. }());
  80078. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  80079. })(BABYLON || (BABYLON = {}));
  80080. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  80081. var BABYLON;
  80082. (function (BABYLON) {
  80083. /**
  80084. * This represents a set of one or more post processes in Babylon.
  80085. * A post process can be used to apply a shader to a texture after it is rendered.
  80086. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  80087. */
  80088. var PostProcessRenderEffect = /** @class */ (function () {
  80089. /**
  80090. * Instantiates a post process render effect.
  80091. * A post process can be used to apply a shader to a texture after it is rendered.
  80092. * @param engine The engine the effect is tied to
  80093. * @param name The name of the effect
  80094. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  80095. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  80096. */
  80097. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  80098. this._name = name;
  80099. this._singleInstance = singleInstance || true;
  80100. this._getPostProcesses = getPostProcesses;
  80101. this._cameras = {};
  80102. this._indicesForCamera = {};
  80103. this._postProcesses = {};
  80104. }
  80105. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  80106. /**
  80107. * Checks if all the post processes in the effect are supported.
  80108. */
  80109. get: function () {
  80110. for (var index in this._postProcesses) {
  80111. if (this._postProcesses.hasOwnProperty(index)) {
  80112. var pps = this._postProcesses[index];
  80113. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  80114. if (!pps[ppIndex].isSupported) {
  80115. return false;
  80116. }
  80117. }
  80118. }
  80119. }
  80120. return true;
  80121. },
  80122. enumerable: true,
  80123. configurable: true
  80124. });
  80125. /**
  80126. * Updates the current state of the effect
  80127. * @hidden
  80128. */
  80129. PostProcessRenderEffect.prototype._update = function () {
  80130. };
  80131. /**
  80132. * Attaches the effect on cameras
  80133. * @param cameras The camera to attach to.
  80134. * @hidden
  80135. */
  80136. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  80137. var _this = this;
  80138. var cameraKey;
  80139. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80140. if (!cams) {
  80141. return;
  80142. }
  80143. for (var i = 0; i < cams.length; i++) {
  80144. var camera = cams[i];
  80145. var cameraName = camera.name;
  80146. if (this._singleInstance) {
  80147. cameraKey = 0;
  80148. }
  80149. else {
  80150. cameraKey = cameraName;
  80151. }
  80152. if (!this._postProcesses[cameraKey]) {
  80153. var postProcess = this._getPostProcesses();
  80154. if (postProcess) {
  80155. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  80156. }
  80157. }
  80158. if (!this._indicesForCamera[cameraName]) {
  80159. this._indicesForCamera[cameraName] = [];
  80160. }
  80161. this._postProcesses[cameraKey].forEach(function (postProcess) {
  80162. var index = camera.attachPostProcess(postProcess);
  80163. _this._indicesForCamera[cameraName].push(index);
  80164. });
  80165. if (!this._cameras[cameraName]) {
  80166. this._cameras[cameraName] = camera;
  80167. }
  80168. }
  80169. };
  80170. /**
  80171. * Detatches the effect on cameras
  80172. * @param cameras The camera to detatch from.
  80173. * @hidden
  80174. */
  80175. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  80176. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80177. if (!cams) {
  80178. return;
  80179. }
  80180. for (var i = 0; i < cams.length; i++) {
  80181. var camera = cams[i];
  80182. var cameraName = camera.name;
  80183. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80184. camera.detachPostProcess(postProcess);
  80185. });
  80186. if (this._cameras[cameraName]) {
  80187. //this._indicesForCamera.splice(index, 1);
  80188. this._cameras[cameraName] = null;
  80189. }
  80190. }
  80191. };
  80192. /**
  80193. * Enables the effect on given cameras
  80194. * @param cameras The camera to enable.
  80195. * @hidden
  80196. */
  80197. PostProcessRenderEffect.prototype._enable = function (cameras) {
  80198. var _this = this;
  80199. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80200. if (!cams) {
  80201. return;
  80202. }
  80203. for (var i = 0; i < cams.length; i++) {
  80204. var camera = cams[i];
  80205. var cameraName = camera.name;
  80206. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  80207. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  80208. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80209. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  80210. });
  80211. }
  80212. }
  80213. }
  80214. };
  80215. /**
  80216. * Disables the effect on the given cameras
  80217. * @param cameras The camera to disable.
  80218. * @hidden
  80219. */
  80220. PostProcessRenderEffect.prototype._disable = function (cameras) {
  80221. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80222. if (!cams) {
  80223. return;
  80224. }
  80225. for (var i = 0; i < cams.length; i++) {
  80226. var camera = cams[i];
  80227. var cameraName = camera.name;
  80228. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  80229. camera.detachPostProcess(postProcess);
  80230. });
  80231. }
  80232. };
  80233. /**
  80234. * Gets a list of the post processes contained in the effect.
  80235. * @param camera The camera to get the post processes on.
  80236. * @returns The list of the post processes in the effect.
  80237. */
  80238. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  80239. if (this._singleInstance) {
  80240. return this._postProcesses[0];
  80241. }
  80242. else {
  80243. if (!camera) {
  80244. return null;
  80245. }
  80246. return this._postProcesses[camera.name];
  80247. }
  80248. };
  80249. return PostProcessRenderEffect;
  80250. }());
  80251. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  80252. })(BABYLON || (BABYLON = {}));
  80253. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  80254. var BABYLON;
  80255. (function (BABYLON) {
  80256. var PostProcessRenderPipeline = /** @class */ (function () {
  80257. function PostProcessRenderPipeline(engine, name) {
  80258. this.engine = engine;
  80259. this._name = name;
  80260. this._renderEffects = {};
  80261. this._renderEffectsForIsolatedPass = new Array();
  80262. this._cameras = [];
  80263. }
  80264. PostProcessRenderPipeline.prototype.getClassName = function () {
  80265. return "PostProcessRenderPipeline";
  80266. };
  80267. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  80268. get: function () {
  80269. for (var renderEffectName in this._renderEffects) {
  80270. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80271. if (!this._renderEffects[renderEffectName].isSupported) {
  80272. return false;
  80273. }
  80274. }
  80275. }
  80276. return true;
  80277. },
  80278. enumerable: true,
  80279. configurable: true
  80280. });
  80281. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  80282. this._renderEffects[renderEffect._name] = renderEffect;
  80283. };
  80284. // private
  80285. /** @hidden */
  80286. PostProcessRenderPipeline.prototype._rebuild = function () {
  80287. };
  80288. /** @hidden */
  80289. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  80290. var renderEffects = this._renderEffects[renderEffectName];
  80291. if (!renderEffects) {
  80292. return;
  80293. }
  80294. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80295. };
  80296. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  80297. var renderEffects = this._renderEffects[renderEffectName];
  80298. if (!renderEffects) {
  80299. return;
  80300. }
  80301. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  80302. };
  80303. /** @hidden */
  80304. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  80305. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80306. if (!cams) {
  80307. return;
  80308. }
  80309. var indicesToDelete = [];
  80310. var i;
  80311. for (i = 0; i < cams.length; i++) {
  80312. var camera = cams[i];
  80313. var cameraName = camera.name;
  80314. if (this._cameras.indexOf(camera) === -1) {
  80315. this._cameras[cameraName] = camera;
  80316. }
  80317. else if (unique) {
  80318. indicesToDelete.push(i);
  80319. }
  80320. }
  80321. for (i = 0; i < indicesToDelete.length; i++) {
  80322. cameras.splice(indicesToDelete[i], 1);
  80323. }
  80324. for (var renderEffectName in this._renderEffects) {
  80325. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80326. this._renderEffects[renderEffectName]._attachCameras(cams);
  80327. }
  80328. }
  80329. };
  80330. /** @hidden */
  80331. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  80332. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  80333. if (!cams) {
  80334. return;
  80335. }
  80336. for (var renderEffectName in this._renderEffects) {
  80337. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80338. this._renderEffects[renderEffectName]._detachCameras(cams);
  80339. }
  80340. }
  80341. for (var i = 0; i < cams.length; i++) {
  80342. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  80343. }
  80344. };
  80345. /** @hidden */
  80346. PostProcessRenderPipeline.prototype._update = function () {
  80347. for (var renderEffectName in this._renderEffects) {
  80348. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  80349. this._renderEffects[renderEffectName]._update();
  80350. }
  80351. }
  80352. for (var i = 0; i < this._cameras.length; i++) {
  80353. var cameraName = this._cameras[i].name;
  80354. if (this._renderEffectsForIsolatedPass[cameraName]) {
  80355. this._renderEffectsForIsolatedPass[cameraName]._update();
  80356. }
  80357. }
  80358. };
  80359. /** @hidden */
  80360. PostProcessRenderPipeline.prototype._reset = function () {
  80361. this._renderEffects = {};
  80362. this._renderEffectsForIsolatedPass = new Array();
  80363. };
  80364. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  80365. // 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)
  80366. var effectKeys = Object.keys(this._renderEffects);
  80367. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  80368. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  80369. if (postProcesses) {
  80370. postProcesses[0].samples = sampleCount;
  80371. return true;
  80372. }
  80373. }
  80374. return false;
  80375. };
  80376. PostProcessRenderPipeline.prototype.dispose = function () {
  80377. // Must be implemented by children
  80378. };
  80379. __decorate([
  80380. BABYLON.serialize()
  80381. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  80382. return PostProcessRenderPipeline;
  80383. }());
  80384. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  80385. })(BABYLON || (BABYLON = {}));
  80386. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  80387. var BABYLON;
  80388. (function (BABYLON) {
  80389. /**
  80390. * This represents a depth renderer in Babylon.
  80391. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  80392. */
  80393. var DepthRenderer = /** @class */ (function () {
  80394. /**
  80395. * Instantiates a depth renderer
  80396. * @param scene The scene the renderer belongs to
  80397. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  80398. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  80399. */
  80400. function DepthRenderer(scene, type, camera) {
  80401. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  80402. if (camera === void 0) { camera = null; }
  80403. var _this = this;
  80404. /**
  80405. * Specifiess that the depth renderer will only be used within
  80406. * the camera it is created for.
  80407. * This can help forcing its rendering during the camera processing.
  80408. */
  80409. this.useOnlyInActiveCamera = false;
  80410. this._scene = scene;
  80411. // Register the G Buffer component to the scene.
  80412. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  80413. if (!component) {
  80414. component = new BABYLON.DepthRendererSceneComponent(scene);
  80415. scene._addComponent(component);
  80416. }
  80417. this._camera = camera;
  80418. var engine = scene.getEngine();
  80419. // Render target
  80420. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  80421. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80422. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80423. this._depthMap.refreshRate = 1;
  80424. this._depthMap.renderParticles = false;
  80425. this._depthMap.renderList = null;
  80426. // Camera to get depth map from to support multiple concurrent cameras
  80427. this._depthMap.activeCamera = this._camera;
  80428. this._depthMap.ignoreCameraViewport = true;
  80429. this._depthMap.useCameraPostProcesses = false;
  80430. // set default depth value to 1.0 (far away)
  80431. this._depthMap.onClearObservable.add(function (engine) {
  80432. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  80433. });
  80434. // Custom render function
  80435. var renderSubMesh = function (subMesh) {
  80436. var mesh = subMesh.getRenderingMesh();
  80437. var scene = _this._scene;
  80438. var engine = scene.getEngine();
  80439. var material = subMesh.getMaterial();
  80440. if (!material) {
  80441. return;
  80442. }
  80443. // Culling and reverse (right handed system)
  80444. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80445. // Managing instances
  80446. var batch = mesh._getInstancesRenderList(subMesh._id);
  80447. if (batch.mustReturn) {
  80448. return;
  80449. }
  80450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80451. var camera = _this._camera || scene.activeCamera;
  80452. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  80453. engine.enableEffect(_this._effect);
  80454. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80455. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80456. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  80457. // Alpha test
  80458. if (material && material.needAlphaTesting()) {
  80459. var alphaTexture = material.getAlphaTestTexture();
  80460. if (alphaTexture) {
  80461. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80462. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80463. }
  80464. }
  80465. // Bones
  80466. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80467. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80468. }
  80469. // Draw
  80470. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80471. }
  80472. };
  80473. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80474. var index;
  80475. if (depthOnlySubMeshes.length) {
  80476. engine.setColorWrite(false);
  80477. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80478. renderSubMesh(depthOnlySubMeshes.data[index]);
  80479. }
  80480. engine.setColorWrite(true);
  80481. }
  80482. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80483. renderSubMesh(opaqueSubMeshes.data[index]);
  80484. }
  80485. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80486. renderSubMesh(alphaTestSubMeshes.data[index]);
  80487. }
  80488. };
  80489. }
  80490. /**
  80491. * Creates the depth rendering effect and checks if the effect is ready.
  80492. * @param subMesh The submesh to be used to render the depth map of
  80493. * @param useInstances If multiple world instances should be used
  80494. * @returns if the depth renderer is ready to render the depth map
  80495. */
  80496. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  80497. var material = subMesh.getMaterial();
  80498. if (material.disableDepthWrite) {
  80499. return false;
  80500. }
  80501. var defines = [];
  80502. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80503. var mesh = subMesh.getMesh();
  80504. // Alpha test
  80505. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  80506. defines.push("#define ALPHATEST");
  80507. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80508. attribs.push(BABYLON.VertexBuffer.UVKind);
  80509. defines.push("#define UV1");
  80510. }
  80511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80512. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80513. defines.push("#define UV2");
  80514. }
  80515. }
  80516. // Bones
  80517. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80518. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80519. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80520. if (mesh.numBoneInfluencers > 4) {
  80521. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80522. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80523. }
  80524. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80525. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80526. }
  80527. else {
  80528. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80529. }
  80530. // Instances
  80531. if (useInstances) {
  80532. defines.push("#define INSTANCES");
  80533. attribs.push("world0");
  80534. attribs.push("world1");
  80535. attribs.push("world2");
  80536. attribs.push("world3");
  80537. }
  80538. // Get correct effect
  80539. var join = defines.join("\n");
  80540. if (this._cachedDefines !== join) {
  80541. this._cachedDefines = join;
  80542. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  80543. }
  80544. return this._effect.isReady();
  80545. };
  80546. /**
  80547. * Gets the texture which the depth map will be written to.
  80548. * @returns The depth map texture
  80549. */
  80550. DepthRenderer.prototype.getDepthMap = function () {
  80551. return this._depthMap;
  80552. };
  80553. /**
  80554. * Disposes of the depth renderer.
  80555. */
  80556. DepthRenderer.prototype.dispose = function () {
  80557. this._depthMap.dispose();
  80558. };
  80559. return DepthRenderer;
  80560. }());
  80561. BABYLON.DepthRenderer = DepthRenderer;
  80562. })(BABYLON || (BABYLON = {}));
  80563. //# sourceMappingURL=babylon.depthRenderer.js.map
  80564. var BABYLON;
  80565. (function (BABYLON) {
  80566. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  80567. camera = camera || this.activeCamera;
  80568. if (!camera) {
  80569. throw "No camera available to enable depth renderer";
  80570. }
  80571. if (!this._depthRenderer) {
  80572. this._depthRenderer = {};
  80573. }
  80574. if (!this._depthRenderer[camera.id]) {
  80575. var textureType = 0;
  80576. if (this.getEngine().getCaps().textureHalfFloatRender) {
  80577. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80578. }
  80579. else if (this.getEngine().getCaps().textureFloatRender) {
  80580. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80581. }
  80582. else {
  80583. throw "Depth renderer does not support int texture type";
  80584. }
  80585. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  80586. }
  80587. return this._depthRenderer[camera.id];
  80588. };
  80589. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  80590. camera = camera || this.activeCamera;
  80591. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  80592. return;
  80593. }
  80594. this._depthRenderer[camera.id].dispose();
  80595. delete this._depthRenderer[camera.id];
  80596. };
  80597. /**
  80598. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  80599. * in several rendering techniques.
  80600. */
  80601. var DepthRendererSceneComponent = /** @class */ (function () {
  80602. /**
  80603. * Creates a new instance of the component for the given scene
  80604. * @param scene Defines the scene to register the component in
  80605. */
  80606. function DepthRendererSceneComponent(scene) {
  80607. /**
  80608. * The component name helpfull to identify the component in the list of scene components.
  80609. */
  80610. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  80611. this.scene = scene;
  80612. }
  80613. /**
  80614. * Registers the component in a given scene
  80615. */
  80616. DepthRendererSceneComponent.prototype.register = function () {
  80617. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  80618. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  80619. };
  80620. /**
  80621. * Rebuilds the elements related to this component in case of
  80622. * context lost for instance.
  80623. */
  80624. DepthRendererSceneComponent.prototype.rebuild = function () {
  80625. // Nothing to do for this component
  80626. };
  80627. /**
  80628. * Disposes the component and the associated ressources
  80629. */
  80630. DepthRendererSceneComponent.prototype.dispose = function () {
  80631. for (var key in this.scene._depthRenderer) {
  80632. this.scene._depthRenderer[key].dispose();
  80633. }
  80634. };
  80635. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80636. if (this.scene._depthRenderer) {
  80637. for (var key in this.scene._depthRenderer) {
  80638. var depthRenderer = this.scene._depthRenderer[key];
  80639. if (!depthRenderer.useOnlyInActiveCamera) {
  80640. renderTargets.push(depthRenderer.getDepthMap());
  80641. }
  80642. }
  80643. }
  80644. };
  80645. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  80646. if (this.scene._depthRenderer) {
  80647. for (var key in this.scene._depthRenderer) {
  80648. var depthRenderer = this.scene._depthRenderer[key];
  80649. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  80650. renderTargets.push(depthRenderer.getDepthMap());
  80651. }
  80652. }
  80653. }
  80654. };
  80655. return DepthRendererSceneComponent;
  80656. }());
  80657. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  80658. })(BABYLON || (BABYLON = {}));
  80659. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  80660. var BABYLON;
  80661. (function (BABYLON) {
  80662. /**
  80663. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  80664. */
  80665. var GeometryBufferRenderer = /** @class */ (function () {
  80666. /**
  80667. * Creates a new G Buffer for the scene
  80668. * @param scene The scene the buffer belongs to
  80669. * @param ratio How big is the buffer related to the main canvas.
  80670. */
  80671. function GeometryBufferRenderer(scene, ratio) {
  80672. if (ratio === void 0) { ratio = 1; }
  80673. this._enablePosition = false;
  80674. this._scene = scene;
  80675. this._ratio = ratio;
  80676. // Register the G Buffer component to the scene.
  80677. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  80678. if (!component) {
  80679. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  80680. scene._addComponent(component);
  80681. }
  80682. // Render target
  80683. this._createRenderTargets();
  80684. }
  80685. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  80686. /**
  80687. * Set the render list (meshes to be rendered) used in the G buffer.
  80688. */
  80689. set: function (meshes) {
  80690. this._multiRenderTarget.renderList = meshes;
  80691. },
  80692. enumerable: true,
  80693. configurable: true
  80694. });
  80695. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  80696. /**
  80697. * Gets wether or not G buffer are supported by the running hardware.
  80698. * This requires draw buffer supports
  80699. */
  80700. get: function () {
  80701. return this._multiRenderTarget.isSupported;
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  80707. /**
  80708. * Gets wether or not position are enabled for the G buffer.
  80709. */
  80710. get: function () {
  80711. return this._enablePosition;
  80712. },
  80713. /**
  80714. * Sets wether or not position are enabled for the G buffer.
  80715. */
  80716. set: function (enable) {
  80717. this._enablePosition = enable;
  80718. this.dispose();
  80719. this._createRenderTargets();
  80720. },
  80721. enumerable: true,
  80722. configurable: true
  80723. });
  80724. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  80725. /**
  80726. * Gets the scene associated with the buffer.
  80727. */
  80728. get: function () {
  80729. return this._scene;
  80730. },
  80731. enumerable: true,
  80732. configurable: true
  80733. });
  80734. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  80735. /**
  80736. * Gets the ratio used by the buffer during its creation.
  80737. * How big is the buffer related to the main canvas.
  80738. */
  80739. get: function () {
  80740. return this._ratio;
  80741. },
  80742. enumerable: true,
  80743. configurable: true
  80744. });
  80745. /**
  80746. * Checks wether everything is ready to render a submesh to the G buffer.
  80747. * @param subMesh the submesh to check readiness for
  80748. * @param useInstances is the mesh drawn using instance or not
  80749. * @returns true if ready otherwise false
  80750. */
  80751. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  80752. var material = subMesh.getMaterial();
  80753. if (material && material.disableDepthWrite) {
  80754. return false;
  80755. }
  80756. var defines = [];
  80757. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  80758. var mesh = subMesh.getMesh();
  80759. // Alpha test
  80760. if (material && material.needAlphaTesting()) {
  80761. defines.push("#define ALPHATEST");
  80762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  80763. attribs.push(BABYLON.VertexBuffer.UVKind);
  80764. defines.push("#define UV1");
  80765. }
  80766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80767. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80768. defines.push("#define UV2");
  80769. }
  80770. }
  80771. // Buffers
  80772. if (this._enablePosition) {
  80773. defines.push("#define POSITION");
  80774. }
  80775. // Bones
  80776. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80779. if (mesh.numBoneInfluencers > 4) {
  80780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  80781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  80782. }
  80783. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80784. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  80785. }
  80786. else {
  80787. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80788. }
  80789. // Instances
  80790. if (useInstances) {
  80791. defines.push("#define INSTANCES");
  80792. attribs.push("world0");
  80793. attribs.push("world1");
  80794. attribs.push("world2");
  80795. attribs.push("world3");
  80796. }
  80797. // Get correct effect
  80798. var join = defines.join("\n");
  80799. if (this._cachedDefines !== join) {
  80800. this._cachedDefines = join;
  80801. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  80802. }
  80803. return this._effect.isReady();
  80804. };
  80805. /**
  80806. * Gets the current underlying G Buffer.
  80807. * @returns the buffer
  80808. */
  80809. GeometryBufferRenderer.prototype.getGBuffer = function () {
  80810. return this._multiRenderTarget;
  80811. };
  80812. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  80813. /**
  80814. * Gets the number of samples used to render the buffer (anti aliasing).
  80815. */
  80816. get: function () {
  80817. return this._multiRenderTarget.samples;
  80818. },
  80819. /**
  80820. * Sets the number of samples used to render the buffer (anti aliasing).
  80821. */
  80822. set: function (value) {
  80823. this._multiRenderTarget.samples = value;
  80824. },
  80825. enumerable: true,
  80826. configurable: true
  80827. });
  80828. /**
  80829. * Disposes the renderer and frees up associated resources.
  80830. */
  80831. GeometryBufferRenderer.prototype.dispose = function () {
  80832. this.getGBuffer().dispose();
  80833. };
  80834. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  80835. var _this = this;
  80836. var engine = this._scene.getEngine();
  80837. var count = this._enablePosition ? 3 : 2;
  80838. 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 });
  80839. if (!this.isSupported) {
  80840. return;
  80841. }
  80842. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80843. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80844. this._multiRenderTarget.refreshRate = 1;
  80845. this._multiRenderTarget.renderParticles = false;
  80846. this._multiRenderTarget.renderList = null;
  80847. // set default depth value to 1.0 (far away)
  80848. this._multiRenderTarget.onClearObservable.add(function (engine) {
  80849. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  80850. });
  80851. // Custom render function
  80852. var renderSubMesh = function (subMesh) {
  80853. var mesh = subMesh.getRenderingMesh();
  80854. var scene = _this._scene;
  80855. var engine = scene.getEngine();
  80856. var material = subMesh.getMaterial();
  80857. if (!material) {
  80858. return;
  80859. }
  80860. // Culling
  80861. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  80862. // Managing instances
  80863. var batch = mesh._getInstancesRenderList(subMesh._id);
  80864. if (batch.mustReturn) {
  80865. return;
  80866. }
  80867. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80868. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  80869. engine.enableEffect(_this._effect);
  80870. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  80871. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  80872. _this._effect.setMatrix("view", scene.getViewMatrix());
  80873. // Alpha test
  80874. if (material && material.needAlphaTesting()) {
  80875. var alphaTexture = material.getAlphaTestTexture();
  80876. if (alphaTexture) {
  80877. _this._effect.setTexture("diffuseSampler", alphaTexture);
  80878. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80879. }
  80880. }
  80881. // Bones
  80882. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80883. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80884. }
  80885. // Draw
  80886. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  80887. }
  80888. };
  80889. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80890. var index;
  80891. if (depthOnlySubMeshes.length) {
  80892. engine.setColorWrite(false);
  80893. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80894. renderSubMesh(depthOnlySubMeshes.data[index]);
  80895. }
  80896. engine.setColorWrite(true);
  80897. }
  80898. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80899. renderSubMesh(opaqueSubMeshes.data[index]);
  80900. }
  80901. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80902. renderSubMesh(alphaTestSubMeshes.data[index]);
  80903. }
  80904. };
  80905. };
  80906. return GeometryBufferRenderer;
  80907. }());
  80908. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  80909. })(BABYLON || (BABYLON = {}));
  80910. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  80911. var BABYLON;
  80912. (function (BABYLON) {
  80913. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  80914. get: function () {
  80915. this._geometryBufferRenderer;
  80916. },
  80917. set: function (value) {
  80918. if (value && value.isSupported) {
  80919. this._geometryBufferRenderer = value;
  80920. }
  80921. ;
  80922. },
  80923. enumerable: true,
  80924. configurable: true
  80925. });
  80926. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  80927. if (ratio === void 0) { ratio = 1; }
  80928. if (this._geometryBufferRenderer) {
  80929. return this._geometryBufferRenderer;
  80930. }
  80931. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80932. if (!this._geometryBufferRenderer.isSupported) {
  80933. this._geometryBufferRenderer = null;
  80934. }
  80935. return this._geometryBufferRenderer;
  80936. };
  80937. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80938. if (!this._geometryBufferRenderer) {
  80939. return;
  80940. }
  80941. this._geometryBufferRenderer.dispose();
  80942. this._geometryBufferRenderer = null;
  80943. };
  80944. /**
  80945. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80946. * in several rendering techniques.
  80947. */
  80948. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80949. /**
  80950. * Creates a new instance of the component for the given scene
  80951. * @param scene Defines the scene to register the component in
  80952. */
  80953. function GeometryBufferRendererSceneComponent(scene) {
  80954. /**
  80955. * The component name helpful to identify the component in the list of scene components.
  80956. */
  80957. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80958. this.scene = scene;
  80959. }
  80960. /**
  80961. * Registers the component in a given scene
  80962. */
  80963. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80964. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80965. };
  80966. /**
  80967. * Rebuilds the elements related to this component in case of
  80968. * context lost for instance.
  80969. */
  80970. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80971. // Nothing to do for this component
  80972. };
  80973. /**
  80974. * Disposes the component and the associated ressources
  80975. */
  80976. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80977. // Nothing to do for this component
  80978. };
  80979. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80980. if (this.scene._geometryBufferRenderer) {
  80981. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80982. }
  80983. };
  80984. return GeometryBufferRendererSceneComponent;
  80985. }());
  80986. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80987. })(BABYLON || (BABYLON = {}));
  80988. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80989. var BABYLON;
  80990. (function (BABYLON) {
  80991. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80992. __extends(SSAORenderingPipeline, _super);
  80993. /**
  80994. * @constructor
  80995. * @param {string} name - The rendering pipeline name
  80996. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80997. * @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 }
  80998. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80999. */
  81000. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  81001. var _this = _super.call(this, scene.getEngine(), name) || this;
  81002. // Members
  81003. /**
  81004. * The PassPostProcess id in the pipeline that contains the original scene color
  81005. */
  81006. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81007. /**
  81008. * The SSAO PostProcess id in the pipeline
  81009. */
  81010. _this.SSAORenderEffect = "SSAORenderEffect";
  81011. /**
  81012. * The horizontal blur PostProcess id in the pipeline
  81013. */
  81014. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81015. /**
  81016. * The vertical blur PostProcess id in the pipeline
  81017. */
  81018. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81019. /**
  81020. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81021. */
  81022. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81023. /**
  81024. * The output strength of the SSAO post-process. Default value is 1.0.
  81025. */
  81026. _this.totalStrength = 1.0;
  81027. /**
  81028. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  81029. */
  81030. _this.radius = 0.0001;
  81031. /**
  81032. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  81033. * Must not be equal to fallOff and superior to fallOff.
  81034. * Default value is 0.975
  81035. */
  81036. _this.area = 0.0075;
  81037. /**
  81038. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  81039. * Must not be equal to area and inferior to area.
  81040. * Default value is 0.0
  81041. */
  81042. _this.fallOff = 0.000001;
  81043. /**
  81044. * The base color of the SSAO post-process
  81045. * The final result is "base + ssao" between [0, 1]
  81046. */
  81047. _this.base = 0.5;
  81048. _this._firstUpdate = true;
  81049. _this._scene = scene;
  81050. // Set up assets
  81051. _this._createRandomTexture();
  81052. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81053. var ssaoRatio = ratio.ssaoRatio || ratio;
  81054. var combineRatio = ratio.combineRatio || ratio;
  81055. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81056. _this._createSSAOPostProcess(ssaoRatio);
  81057. _this._createBlurPostProcess(ssaoRatio);
  81058. _this._createSSAOCombinePostProcess(combineRatio);
  81059. // Set up pipeline
  81060. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81061. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81062. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81063. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81064. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81065. // Finish
  81066. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81067. if (cameras)
  81068. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81069. return _this;
  81070. }
  81071. // Public Methods
  81072. /**
  81073. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81074. */
  81075. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81076. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81077. for (var i = 0; i < this._scene.cameras.length; i++) {
  81078. var camera = this._scene.cameras[i];
  81079. this._originalColorPostProcess.dispose(camera);
  81080. this._ssaoPostProcess.dispose(camera);
  81081. this._blurHPostProcess.dispose(camera);
  81082. this._blurVPostProcess.dispose(camera);
  81083. this._ssaoCombinePostProcess.dispose(camera);
  81084. }
  81085. this._randomTexture.dispose();
  81086. if (disableDepthRender)
  81087. this._scene.disableDepthRenderer();
  81088. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81089. _super.prototype.dispose.call(this);
  81090. };
  81091. // Private Methods
  81092. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  81093. var _this = this;
  81094. var size = 16;
  81095. 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);
  81096. 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);
  81097. this._blurHPostProcess.onActivateObservable.add(function () {
  81098. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  81099. _this._blurHPostProcess.kernel = size * dw;
  81100. });
  81101. this._blurVPostProcess.onActivateObservable.add(function () {
  81102. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  81103. _this._blurVPostProcess.kernel = size * dw;
  81104. });
  81105. };
  81106. /** @hidden */
  81107. SSAORenderingPipeline.prototype._rebuild = function () {
  81108. this._firstUpdate = true;
  81109. _super.prototype._rebuild.call(this);
  81110. };
  81111. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81112. var _this = this;
  81113. var numSamples = 16;
  81114. var sampleSphere = [
  81115. 0.5381, 0.1856, -0.4319,
  81116. 0.1379, 0.2486, 0.4430,
  81117. 0.3371, 0.5679, -0.0057,
  81118. -0.6999, -0.0451, -0.0019,
  81119. 0.0689, -0.1598, -0.8547,
  81120. 0.0560, 0.0069, -0.1843,
  81121. -0.0146, 0.1402, 0.0762,
  81122. 0.0100, -0.1924, -0.0344,
  81123. -0.3577, -0.5301, -0.4358,
  81124. -0.3169, 0.1063, 0.0158,
  81125. 0.0103, -0.5869, 0.0046,
  81126. -0.0897, -0.4940, 0.3287,
  81127. 0.7119, -0.0154, -0.0918,
  81128. -0.0533, 0.0596, -0.5411,
  81129. 0.0352, -0.0631, 0.5460,
  81130. -0.4776, 0.2847, -0.0271
  81131. ];
  81132. var samplesFactor = 1.0 / numSamples;
  81133. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  81134. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81135. "area", "fallOff", "base", "range", "viewport"
  81136. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81137. this._ssaoPostProcess.onApply = function (effect) {
  81138. if (_this._firstUpdate) {
  81139. effect.setArray3("sampleSphere", sampleSphere);
  81140. effect.setFloat("samplesFactor", samplesFactor);
  81141. effect.setFloat("randTextureTiles", 4.0);
  81142. }
  81143. effect.setFloat("totalStrength", _this.totalStrength);
  81144. effect.setFloat("radius", _this.radius);
  81145. effect.setFloat("area", _this.area);
  81146. effect.setFloat("fallOff", _this.fallOff);
  81147. effect.setFloat("base", _this.base);
  81148. effect.setTexture("textureSampler", _this._depthTexture);
  81149. effect.setTexture("randomSampler", _this._randomTexture);
  81150. };
  81151. };
  81152. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81153. var _this = this;
  81154. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81155. this._ssaoCombinePostProcess.onApply = function (effect) {
  81156. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  81157. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81158. };
  81159. };
  81160. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  81161. var size = 512;
  81162. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81163. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81164. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81165. var context = this._randomTexture.getContext();
  81166. var rand = function (min, max) {
  81167. return Math.random() * (max - min) + min;
  81168. };
  81169. var randVector = BABYLON.Vector3.Zero();
  81170. for (var x = 0; x < size; x++) {
  81171. for (var y = 0; y < size; y++) {
  81172. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  81173. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  81174. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  81175. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81176. context.fillRect(x, y, 1, 1);
  81177. }
  81178. }
  81179. this._randomTexture.update(false);
  81180. };
  81181. __decorate([
  81182. BABYLON.serialize()
  81183. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  81184. __decorate([
  81185. BABYLON.serialize()
  81186. ], SSAORenderingPipeline.prototype, "radius", void 0);
  81187. __decorate([
  81188. BABYLON.serialize()
  81189. ], SSAORenderingPipeline.prototype, "area", void 0);
  81190. __decorate([
  81191. BABYLON.serialize()
  81192. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  81193. __decorate([
  81194. BABYLON.serialize()
  81195. ], SSAORenderingPipeline.prototype, "base", void 0);
  81196. return SSAORenderingPipeline;
  81197. }(BABYLON.PostProcessRenderPipeline));
  81198. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  81199. })(BABYLON || (BABYLON = {}));
  81200. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  81201. var BABYLON;
  81202. (function (BABYLON) {
  81203. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  81204. __extends(SSAO2RenderingPipeline, _super);
  81205. /**
  81206. * @constructor
  81207. * @param {string} name - The rendering pipeline name
  81208. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81209. * @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 }
  81210. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81211. */
  81212. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  81213. var _this = _super.call(this, scene.getEngine(), name) || this;
  81214. // Members
  81215. /**
  81216. * The PassPostProcess id in the pipeline that contains the original scene color
  81217. */
  81218. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  81219. /**
  81220. * The SSAO PostProcess id in the pipeline
  81221. */
  81222. _this.SSAORenderEffect = "SSAORenderEffect";
  81223. /**
  81224. * The horizontal blur PostProcess id in the pipeline
  81225. */
  81226. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  81227. /**
  81228. * The vertical blur PostProcess id in the pipeline
  81229. */
  81230. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  81231. /**
  81232. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  81233. */
  81234. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  81235. /**
  81236. * The output strength of the SSAO post-process. Default value is 1.0.
  81237. */
  81238. _this.totalStrength = 1.0;
  81239. /**
  81240. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  81241. */
  81242. _this.maxZ = 100.0;
  81243. /**
  81244. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  81245. */
  81246. _this.minZAspect = 0.2;
  81247. _this._samples = 8;
  81248. _this._textureSamples = 1;
  81249. /**
  81250. * Are we using bilateral blur ?
  81251. */
  81252. _this._expensiveBlur = true;
  81253. /**
  81254. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  81255. */
  81256. _this.radius = 2.0;
  81257. /**
  81258. * The base color of the SSAO post-process
  81259. * The final result is "base + ssao" between [0, 1]
  81260. */
  81261. _this.base = 0;
  81262. _this._firstUpdate = true;
  81263. _this._bits = new Uint32Array(1);
  81264. _this._scene = scene;
  81265. _this._ratio = ratio;
  81266. if (!_this.isSupported) {
  81267. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  81268. return _this;
  81269. }
  81270. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  81271. var blurRatio = _this._ratio.blurRatio || ratio;
  81272. // Set up assets
  81273. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  81274. _this._createRandomTexture();
  81275. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  81276. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  81277. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  81278. _this._originalColorPostProcess.samples = _this.textureSamples;
  81279. _this._createSSAOPostProcess(1.0);
  81280. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  81281. _this._createSSAOCombinePostProcess(blurRatio);
  81282. // Set up pipeline
  81283. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  81284. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  81285. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  81286. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  81287. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  81288. // Finish
  81289. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81290. if (cameras)
  81291. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81292. return _this;
  81293. }
  81294. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  81295. get: function () {
  81296. return this._samples;
  81297. },
  81298. /**
  81299. * Number of samples used for the SSAO calculations. Default value is 8
  81300. */
  81301. set: function (n) {
  81302. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  81303. this._samples = n;
  81304. this._sampleSphere = this._generateHemisphere();
  81305. this._firstUpdate = true;
  81306. },
  81307. enumerable: true,
  81308. configurable: true
  81309. });
  81310. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  81311. get: function () {
  81312. return this._textureSamples;
  81313. },
  81314. /**
  81315. * Number of samples to use for antialiasing
  81316. */
  81317. set: function (n) {
  81318. this._textureSamples = n;
  81319. this._originalColorPostProcess.samples = n;
  81320. this._blurHPostProcess.samples = n;
  81321. this._blurVPostProcess.samples = n;
  81322. this._ssaoPostProcess.samples = n;
  81323. this._ssaoCombinePostProcess.samples = n;
  81324. },
  81325. enumerable: true,
  81326. configurable: true
  81327. });
  81328. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  81329. get: function () {
  81330. return this._expensiveBlur;
  81331. },
  81332. set: function (b) {
  81333. 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"]);
  81334. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  81335. this._expensiveBlur = b;
  81336. this._firstUpdate = true;
  81337. },
  81338. enumerable: true,
  81339. configurable: true
  81340. });
  81341. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  81342. /**
  81343. * Support test.
  81344. */
  81345. get: function () {
  81346. var engine = BABYLON.Engine.LastCreatedEngine;
  81347. if (!engine) {
  81348. return false;
  81349. }
  81350. return engine.getCaps().drawBuffersExtension;
  81351. },
  81352. enumerable: true,
  81353. configurable: true
  81354. });
  81355. // Public Methods
  81356. /**
  81357. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  81358. */
  81359. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  81360. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  81361. for (var i = 0; i < this._scene.cameras.length; i++) {
  81362. var camera = this._scene.cameras[i];
  81363. this._originalColorPostProcess.dispose(camera);
  81364. this._ssaoPostProcess.dispose(camera);
  81365. this._blurHPostProcess.dispose(camera);
  81366. this._blurVPostProcess.dispose(camera);
  81367. this._ssaoCombinePostProcess.dispose(camera);
  81368. }
  81369. this._randomTexture.dispose();
  81370. if (disableGeometryBufferRenderer)
  81371. this._scene.disableGeometryBufferRenderer();
  81372. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81373. _super.prototype.dispose.call(this);
  81374. };
  81375. // Private Methods
  81376. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  81377. var _this = this;
  81378. this._samplerOffsets = [];
  81379. var expensive = this.expensiveBlur;
  81380. for (var i = -8; i < 8; i++) {
  81381. this._samplerOffsets.push(i * 2 + 0.5);
  81382. }
  81383. 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");
  81384. this._blurHPostProcess.onApply = function (effect) {
  81385. if (!_this._scene.activeCamera) {
  81386. return;
  81387. }
  81388. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  81389. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81390. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81391. effect.setFloat("radius", _this.radius);
  81392. effect.setTexture("depthSampler", _this._depthTexture);
  81393. if (_this._firstUpdate) {
  81394. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81395. }
  81396. };
  81397. 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");
  81398. this._blurVPostProcess.onApply = function (effect) {
  81399. if (!_this._scene.activeCamera) {
  81400. return;
  81401. }
  81402. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  81403. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81404. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81405. effect.setFloat("radius", _this.radius);
  81406. effect.setTexture("depthSampler", _this._depthTexture);
  81407. if (_this._firstUpdate) {
  81408. effect.setArray("samplerOffsets", _this._samplerOffsets);
  81409. _this._firstUpdate = false;
  81410. }
  81411. };
  81412. this._blurHPostProcess.samples = this.textureSamples;
  81413. this._blurVPostProcess.samples = this.textureSamples;
  81414. };
  81415. /** @hidden */
  81416. SSAO2RenderingPipeline.prototype._rebuild = function () {
  81417. this._firstUpdate = true;
  81418. _super.prototype._rebuild.call(this);
  81419. };
  81420. //Van der Corput radical inverse
  81421. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  81422. this._bits[0] = i;
  81423. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  81424. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  81425. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  81426. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  81427. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  81428. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  81429. };
  81430. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  81431. return [i / n, this._radicalInverse_VdC(i)];
  81432. };
  81433. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  81434. var phi = v * 2.0 * Math.PI;
  81435. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  81436. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  81437. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  81438. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  81439. };
  81440. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  81441. var numSamples = this.samples;
  81442. var result = [];
  81443. var vector;
  81444. var i = 0;
  81445. while (i < numSamples) {
  81446. if (numSamples < 16) {
  81447. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  81448. }
  81449. else {
  81450. var rand = this._hammersley(i, numSamples);
  81451. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  81452. }
  81453. result.push(vector.x, vector.y, vector.z);
  81454. i++;
  81455. }
  81456. return result;
  81457. };
  81458. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  81459. var _this = this;
  81460. var numSamples = this.samples;
  81461. this._sampleSphere = this._generateHemisphere();
  81462. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  81463. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  81464. "base", "range", "projection", "near", "far", "texelSize",
  81465. "xViewport", "yViewport", "maxZ", "minZAspect"
  81466. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  81467. this._ssaoPostProcess.onApply = function (effect) {
  81468. if (_this._firstUpdate) {
  81469. effect.setArray3("sampleSphere", _this._sampleSphere);
  81470. effect.setFloat("randTextureTiles", 32.0);
  81471. }
  81472. if (!_this._scene.activeCamera) {
  81473. return;
  81474. }
  81475. effect.setFloat("samplesFactor", 1 / _this.samples);
  81476. effect.setFloat("totalStrength", _this.totalStrength);
  81477. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  81478. effect.setFloat("radius", _this.radius);
  81479. effect.setFloat("maxZ", _this.maxZ);
  81480. effect.setFloat("minZAspect", _this.minZAspect);
  81481. effect.setFloat("base", _this.base);
  81482. effect.setFloat("near", _this._scene.activeCamera.minZ);
  81483. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  81484. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  81485. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  81486. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  81487. effect.setTexture("textureSampler", _this._depthTexture);
  81488. effect.setTexture("normalSampler", _this._normalTexture);
  81489. effect.setTexture("randomSampler", _this._randomTexture);
  81490. };
  81491. this._ssaoPostProcess.samples = this.textureSamples;
  81492. };
  81493. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  81494. var _this = this;
  81495. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81496. this._ssaoCombinePostProcess.onApply = function (effect) {
  81497. var viewport = _this._scene.activeCamera.viewport;
  81498. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  81499. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  81500. };
  81501. this._ssaoCombinePostProcess.samples = this.textureSamples;
  81502. };
  81503. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  81504. var size = 128;
  81505. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81506. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81507. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81508. var context = this._randomTexture.getContext();
  81509. var rand = function (min, max) {
  81510. return Math.random() * (max - min) + min;
  81511. };
  81512. var randVector = BABYLON.Vector3.Zero();
  81513. for (var x = 0; x < size; x++) {
  81514. for (var y = 0; y < size; y++) {
  81515. randVector.x = rand(0.0, 1.0);
  81516. randVector.y = rand(0.0, 1.0);
  81517. randVector.z = 0.0;
  81518. randVector.normalize();
  81519. randVector.scaleInPlace(255);
  81520. randVector.x = Math.floor(randVector.x);
  81521. randVector.y = Math.floor(randVector.y);
  81522. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  81523. context.fillRect(x, y, 1, 1);
  81524. }
  81525. }
  81526. this._randomTexture.update(false);
  81527. };
  81528. /**
  81529. * Serialize the rendering pipeline (Used when exporting)
  81530. * @returns the serialized object
  81531. */
  81532. SSAO2RenderingPipeline.prototype.serialize = function () {
  81533. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81534. serializationObject.customType = "SSAO2RenderingPipeline";
  81535. return serializationObject;
  81536. };
  81537. /**
  81538. * Parse the serialized pipeline
  81539. * @param source Source pipeline.
  81540. * @param scene The scene to load the pipeline to.
  81541. * @param rootUrl The URL of the serialized pipeline.
  81542. * @returns An instantiated pipeline from the serialized object.
  81543. */
  81544. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  81545. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81546. };
  81547. __decorate([
  81548. BABYLON.serialize()
  81549. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  81550. __decorate([
  81551. BABYLON.serialize()
  81552. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  81553. __decorate([
  81554. BABYLON.serialize()
  81555. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  81556. __decorate([
  81557. BABYLON.serialize("samples")
  81558. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  81559. __decorate([
  81560. BABYLON.serialize("textureSamples")
  81561. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  81562. __decorate([
  81563. BABYLON.serialize()
  81564. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  81565. __decorate([
  81566. BABYLON.serialize("expensiveBlur")
  81567. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  81568. __decorate([
  81569. BABYLON.serialize()
  81570. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  81571. __decorate([
  81572. BABYLON.serialize()
  81573. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  81574. return SSAO2RenderingPipeline;
  81575. }(BABYLON.PostProcessRenderPipeline));
  81576. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  81577. })(BABYLON || (BABYLON = {}));
  81578. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  81579. // BABYLON.JS Chromatic Aberration GLSL Shader
  81580. // Author: Olivier Guyot
  81581. // Separates very slightly R, G and B colors on the edges of the screen
  81582. // Inspired by Francois Tarlier & Martins Upitis
  81583. var BABYLON;
  81584. (function (BABYLON) {
  81585. var LensRenderingPipeline = /** @class */ (function (_super) {
  81586. __extends(LensRenderingPipeline, _super);
  81587. /**
  81588. * @constructor
  81589. *
  81590. * Effect parameters are as follow:
  81591. * {
  81592. * chromatic_aberration: number; // from 0 to x (1 for realism)
  81593. * edge_blur: number; // from 0 to x (1 for realism)
  81594. * distortion: number; // from 0 to x (1 for realism)
  81595. * grain_amount: number; // from 0 to 1
  81596. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  81597. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  81598. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  81599. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  81600. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  81601. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  81602. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  81603. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  81604. * }
  81605. * Note: if an effect parameter is unset, effect is disabled
  81606. *
  81607. * @param {string} name - The rendering pipeline name
  81608. * @param {object} parameters - An object containing all parameters (see above)
  81609. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81610. * @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)
  81611. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81612. */
  81613. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  81614. if (ratio === void 0) { ratio = 1.0; }
  81615. var _this = _super.call(this, scene.getEngine(), name) || this;
  81616. // Lens effects can be of the following:
  81617. // - chromatic aberration (slight shift of RGB colors)
  81618. // - blur on the edge of the lens
  81619. // - lens distortion
  81620. // - depth-of-field blur & highlights enhancing
  81621. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  81622. // - grain effect (noise or custom texture)
  81623. // Two additional texture samplers are needed:
  81624. // - depth map (for depth-of-field)
  81625. // - grain texture
  81626. /**
  81627. * The chromatic aberration PostProcess id in the pipeline
  81628. */
  81629. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  81630. /**
  81631. * The highlights enhancing PostProcess id in the pipeline
  81632. */
  81633. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  81634. /**
  81635. * The depth-of-field PostProcess id in the pipeline
  81636. */
  81637. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  81638. _this._scene = scene;
  81639. // Fetch texture samplers
  81640. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  81641. if (parameters.grain_texture) {
  81642. _this._grainTexture = parameters.grain_texture;
  81643. }
  81644. else {
  81645. _this._createGrainTexture();
  81646. }
  81647. // save parameters
  81648. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  81649. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  81650. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  81651. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  81652. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  81653. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  81654. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  81655. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  81656. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  81657. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  81658. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  81659. // Create effects
  81660. _this._createChromaticAberrationPostProcess(ratio);
  81661. _this._createHighlightsPostProcess(ratio);
  81662. _this._createDepthOfFieldPostProcess(ratio / 4);
  81663. // Set up pipeline
  81664. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  81665. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  81666. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  81667. if (_this._highlightsGain === -1) {
  81668. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  81669. }
  81670. // Finish
  81671. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81672. if (cameras) {
  81673. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  81674. }
  81675. return _this;
  81676. }
  81677. // public methods (self explanatory)
  81678. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  81679. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  81680. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  81681. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  81682. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  81683. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  81684. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  81685. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  81686. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  81687. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  81688. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  81689. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  81690. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  81691. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  81692. };
  81693. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  81694. this._highlightsPostProcess.updateEffect();
  81695. };
  81696. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  81697. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  81698. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  81699. this._highlightsGain = amount;
  81700. };
  81701. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  81702. if (this._highlightsGain === -1) {
  81703. this._highlightsGain = 1.0;
  81704. }
  81705. this._highlightsThreshold = amount;
  81706. };
  81707. LensRenderingPipeline.prototype.disableHighlights = function () {
  81708. this._highlightsGain = -1;
  81709. };
  81710. /**
  81711. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  81712. */
  81713. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  81714. if (disableDepthRender === void 0) { disableDepthRender = false; }
  81715. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  81716. this._chromaticAberrationPostProcess = null;
  81717. this._highlightsPostProcess = null;
  81718. this._depthOfFieldPostProcess = null;
  81719. this._grainTexture.dispose();
  81720. if (disableDepthRender)
  81721. this._scene.disableDepthRenderer();
  81722. };
  81723. // colors shifting and distortion
  81724. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  81725. var _this = this;
  81726. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  81727. [], // samplers
  81728. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81729. this._chromaticAberrationPostProcess.onApply = function (effect) {
  81730. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  81731. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81732. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81733. effect.setFloat('radialIntensity', 1);
  81734. effect.setFloat2('direction', 17, 17);
  81735. effect.setFloat2('centerPosition', 0.5, 0.5);
  81736. };
  81737. };
  81738. // highlights enhancing
  81739. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  81740. var _this = this;
  81741. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  81742. [], // samplers
  81743. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  81744. this._highlightsPostProcess.onApply = function (effect) {
  81745. effect.setFloat('gain', _this._highlightsGain);
  81746. effect.setFloat('threshold', _this._highlightsThreshold);
  81747. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  81748. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81749. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81750. };
  81751. };
  81752. // colors shifting and distortion
  81753. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  81754. var _this = this;
  81755. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  81756. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  81757. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  81758. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  81759. this._depthOfFieldPostProcess.onApply = function (effect) {
  81760. effect.setTexture("depthSampler", _this._depthTexture);
  81761. effect.setTexture("grainSampler", _this._grainTexture);
  81762. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  81763. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  81764. effect.setFloat('grain_amount', _this._grainAmount);
  81765. effect.setBool('blur_noise', _this._blurNoise);
  81766. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  81767. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  81768. effect.setFloat('distortion', _this._distortion);
  81769. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  81770. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  81771. effect.setFloat('aperture', _this._dofAperture);
  81772. effect.setFloat('darken', _this._dofDarken);
  81773. effect.setFloat('edge_blur', _this._edgeBlur);
  81774. effect.setBool('highlights', (_this._highlightsGain !== -1));
  81775. if (_this._scene.activeCamera) {
  81776. effect.setFloat('near', _this._scene.activeCamera.minZ);
  81777. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  81778. }
  81779. };
  81780. };
  81781. // creates a black and white random noise texture, 512x512
  81782. LensRenderingPipeline.prototype._createGrainTexture = function () {
  81783. var size = 512;
  81784. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81785. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  81786. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  81787. var context = this._grainTexture.getContext();
  81788. var rand = function (min, max) {
  81789. return Math.random() * (max - min) + min;
  81790. };
  81791. var value;
  81792. for (var x = 0; x < size; x++) {
  81793. for (var y = 0; y < size; y++) {
  81794. value = Math.floor(rand(0.42, 0.58) * 255);
  81795. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  81796. context.fillRect(x, y, 1, 1);
  81797. }
  81798. }
  81799. this._grainTexture.update(false);
  81800. };
  81801. return LensRenderingPipeline;
  81802. }(BABYLON.PostProcessRenderPipeline));
  81803. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  81804. })(BABYLON || (BABYLON = {}));
  81805. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  81806. var BABYLON;
  81807. (function (BABYLON) {
  81808. var StandardRenderingPipeline = /** @class */ (function (_super) {
  81809. __extends(StandardRenderingPipeline, _super);
  81810. /**
  81811. * @constructor
  81812. * @param {string} name - The rendering pipeline name
  81813. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  81814. * @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)
  81815. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  81816. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  81817. */
  81818. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  81819. if (originalPostProcess === void 0) { originalPostProcess = null; }
  81820. var _this = _super.call(this, scene.getEngine(), name) || this;
  81821. /**
  81822. * Post-process used to down scale an image x4
  81823. */
  81824. _this.downSampleX4PostProcess = null;
  81825. /**
  81826. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  81827. */
  81828. _this.brightPassPostProcess = null;
  81829. /**
  81830. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  81831. */
  81832. _this.blurHPostProcesses = [];
  81833. /**
  81834. * Post-process array storing all the vertical blur post-processes used by the pipeline
  81835. */
  81836. _this.blurVPostProcesses = [];
  81837. /**
  81838. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  81839. */
  81840. _this.textureAdderPostProcess = null;
  81841. /**
  81842. * Post-process used to create volumetric lighting effect
  81843. */
  81844. _this.volumetricLightPostProcess = null;
  81845. /**
  81846. * Post-process used to smooth the previous volumetric light post-process on the X axis
  81847. */
  81848. _this.volumetricLightSmoothXPostProcess = null;
  81849. /**
  81850. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  81851. */
  81852. _this.volumetricLightSmoothYPostProcess = null;
  81853. /**
  81854. * Post-process used to merge the volumetric light effect and the real scene color
  81855. */
  81856. _this.volumetricLightMergePostProces = null;
  81857. /**
  81858. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  81859. */
  81860. _this.volumetricLightFinalPostProcess = null;
  81861. /**
  81862. * Base post-process used to calculate the average luminance of the final image for HDR
  81863. */
  81864. _this.luminancePostProcess = null;
  81865. /**
  81866. * Post-processes used to create down sample post-processes in order to get
  81867. * the average luminance of the final image for HDR
  81868. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  81869. */
  81870. _this.luminanceDownSamplePostProcesses = [];
  81871. /**
  81872. * Post-process used to create a HDR effect (light adaptation)
  81873. */
  81874. _this.hdrPostProcess = null;
  81875. /**
  81876. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  81877. */
  81878. _this.textureAdderFinalPostProcess = null;
  81879. /**
  81880. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  81881. */
  81882. _this.lensFlareFinalPostProcess = null;
  81883. /**
  81884. * Post-process used to merge the final HDR post-process and the real scene color
  81885. */
  81886. _this.hdrFinalPostProcess = null;
  81887. /**
  81888. * Post-process used to create a lens flare effect
  81889. */
  81890. _this.lensFlarePostProcess = null;
  81891. /**
  81892. * Post-process that merges the result of the lens flare post-process and the real scene color
  81893. */
  81894. _this.lensFlareComposePostProcess = null;
  81895. /**
  81896. * Post-process used to create a motion blur effect
  81897. */
  81898. _this.motionBlurPostProcess = null;
  81899. /**
  81900. * Post-process used to create a depth of field effect
  81901. */
  81902. _this.depthOfFieldPostProcess = null;
  81903. /**
  81904. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  81905. */
  81906. _this.fxaaPostProcess = null;
  81907. // Values
  81908. /**
  81909. * Represents the brightness threshold in order to configure the illuminated surfaces
  81910. */
  81911. _this.brightThreshold = 1.0;
  81912. /**
  81913. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  81914. */
  81915. _this.blurWidth = 512.0;
  81916. /**
  81917. * Sets if the blur for highlighted surfaces must be only horizontal
  81918. */
  81919. _this.horizontalBlur = false;
  81920. /**
  81921. * Sets the overall exposure used by the pipeline
  81922. */
  81923. _this.exposure = 1.0;
  81924. /**
  81925. * Texture used typically to simulate "dirty" on camera lens
  81926. */
  81927. _this.lensTexture = null;
  81928. /**
  81929. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  81930. */
  81931. _this.volumetricLightCoefficient = 0.2;
  81932. /**
  81933. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81934. */
  81935. _this.volumetricLightPower = 4.0;
  81936. /**
  81937. * Used the set the blur intensity to smooth the volumetric lights
  81938. */
  81939. _this.volumetricLightBlurScale = 64.0;
  81940. /**
  81941. * Light (spot or directional) used to generate the volumetric lights rays
  81942. * The source light must have a shadow generate so the pipeline can get its
  81943. * depth map
  81944. */
  81945. _this.sourceLight = null;
  81946. /**
  81947. * For eye adaptation, represents the minimum luminance the eye can see
  81948. */
  81949. _this.hdrMinimumLuminance = 1.0;
  81950. /**
  81951. * For eye adaptation, represents the decrease luminance speed
  81952. */
  81953. _this.hdrDecreaseRate = 0.5;
  81954. /**
  81955. * For eye adaptation, represents the increase luminance speed
  81956. */
  81957. _this.hdrIncreaseRate = 0.5;
  81958. /**
  81959. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81960. */
  81961. _this.lensColorTexture = null;
  81962. /**
  81963. * The overall strengh for the lens flare effect
  81964. */
  81965. _this.lensFlareStrength = 20.0;
  81966. /**
  81967. * Dispersion coefficient for lens flare ghosts
  81968. */
  81969. _this.lensFlareGhostDispersal = 1.4;
  81970. /**
  81971. * Main lens flare halo width
  81972. */
  81973. _this.lensFlareHaloWidth = 0.7;
  81974. /**
  81975. * Based on the lens distortion effect, defines how much the lens flare result
  81976. * is distorted
  81977. */
  81978. _this.lensFlareDistortionStrength = 16.0;
  81979. /**
  81980. * Lens star texture must be used to simulate rays on the flares and is available
  81981. * in the documentation
  81982. */
  81983. _this.lensStarTexture = null;
  81984. /**
  81985. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81986. * flare effect by taking account of the dirt texture
  81987. */
  81988. _this.lensFlareDirtTexture = null;
  81989. /**
  81990. * Represents the focal length for the depth of field effect
  81991. */
  81992. _this.depthOfFieldDistance = 10.0;
  81993. /**
  81994. * Represents the blur intensity for the blurred part of the depth of field effect
  81995. */
  81996. _this.depthOfFieldBlurWidth = 64.0;
  81997. /**
  81998. * For motion blur, defines how much the image is blurred by the movement
  81999. */
  82000. _this.motionStrength = 1.0;
  82001. /**
  82002. * List of animations for the pipeline (IAnimatable implementation)
  82003. */
  82004. _this.animations = [];
  82005. _this._currentDepthOfFieldSource = null;
  82006. _this._hdrCurrentLuminance = 1.0;
  82007. // Getters and setters
  82008. _this._bloomEnabled = false;
  82009. _this._depthOfFieldEnabled = false;
  82010. _this._vlsEnabled = false;
  82011. _this._lensFlareEnabled = false;
  82012. _this._hdrEnabled = false;
  82013. _this._motionBlurEnabled = false;
  82014. _this._fxaaEnabled = false;
  82015. _this._motionBlurSamples = 64.0;
  82016. _this._volumetricLightStepsCount = 50.0;
  82017. _this._samples = 1;
  82018. _this._cameras = cameras || [];
  82019. // Initialize
  82020. _this._scene = scene;
  82021. _this._basePostProcess = originalPostProcess;
  82022. _this._ratio = ratio;
  82023. // Misc
  82024. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82025. // Finish
  82026. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82027. _this._buildPipeline();
  82028. return _this;
  82029. }
  82030. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  82031. /**
  82032. * Specifies if the bloom pipeline is enabled
  82033. */
  82034. get: function () {
  82035. return this._bloomEnabled;
  82036. },
  82037. set: function (enabled) {
  82038. if (this._bloomEnabled === enabled) {
  82039. return;
  82040. }
  82041. this._bloomEnabled = enabled;
  82042. this._buildPipeline();
  82043. },
  82044. enumerable: true,
  82045. configurable: true
  82046. });
  82047. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  82048. /**
  82049. * Specifies if the depth of field pipeline is enabed
  82050. */
  82051. get: function () {
  82052. return this._depthOfFieldEnabled;
  82053. },
  82054. set: function (enabled) {
  82055. if (this._depthOfFieldEnabled === enabled) {
  82056. return;
  82057. }
  82058. this._depthOfFieldEnabled = enabled;
  82059. this._buildPipeline();
  82060. },
  82061. enumerable: true,
  82062. configurable: true
  82063. });
  82064. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  82065. /**
  82066. * Specifies if the lens flare pipeline is enabed
  82067. */
  82068. get: function () {
  82069. return this._lensFlareEnabled;
  82070. },
  82071. set: function (enabled) {
  82072. if (this._lensFlareEnabled === enabled) {
  82073. return;
  82074. }
  82075. this._lensFlareEnabled = enabled;
  82076. this._buildPipeline();
  82077. },
  82078. enumerable: true,
  82079. configurable: true
  82080. });
  82081. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  82082. /**
  82083. * Specifies if the HDR pipeline is enabled
  82084. */
  82085. get: function () {
  82086. return this._hdrEnabled;
  82087. },
  82088. set: function (enabled) {
  82089. if (this._hdrEnabled === enabled) {
  82090. return;
  82091. }
  82092. this._hdrEnabled = enabled;
  82093. this._buildPipeline();
  82094. },
  82095. enumerable: true,
  82096. configurable: true
  82097. });
  82098. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  82099. /**
  82100. * Specifies if the volumetric lights scattering effect is enabled
  82101. */
  82102. get: function () {
  82103. return this._vlsEnabled;
  82104. },
  82105. set: function (enabled) {
  82106. if (this._vlsEnabled === enabled) {
  82107. return;
  82108. }
  82109. if (enabled) {
  82110. var geometry = this._scene.enableGeometryBufferRenderer();
  82111. if (!geometry) {
  82112. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  82113. return;
  82114. }
  82115. }
  82116. this._vlsEnabled = enabled;
  82117. this._buildPipeline();
  82118. },
  82119. enumerable: true,
  82120. configurable: true
  82121. });
  82122. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  82123. /**
  82124. * Specifies if the motion blur effect is enabled
  82125. */
  82126. get: function () {
  82127. return this._motionBlurEnabled;
  82128. },
  82129. set: function (enabled) {
  82130. if (this._motionBlurEnabled === enabled) {
  82131. return;
  82132. }
  82133. this._motionBlurEnabled = enabled;
  82134. this._buildPipeline();
  82135. },
  82136. enumerable: true,
  82137. configurable: true
  82138. });
  82139. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  82140. /**
  82141. * Specifies if anti-aliasing is enabled
  82142. */
  82143. get: function () {
  82144. return this._fxaaEnabled;
  82145. },
  82146. set: function (enabled) {
  82147. if (this._fxaaEnabled === enabled) {
  82148. return;
  82149. }
  82150. this._fxaaEnabled = enabled;
  82151. this._buildPipeline();
  82152. },
  82153. enumerable: true,
  82154. configurable: true
  82155. });
  82156. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  82157. /**
  82158. * Specifies the number of steps used to calculate the volumetric lights
  82159. * Typically in interval [50, 200]
  82160. */
  82161. get: function () {
  82162. return this._volumetricLightStepsCount;
  82163. },
  82164. set: function (count) {
  82165. if (this.volumetricLightPostProcess) {
  82166. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  82167. }
  82168. this._volumetricLightStepsCount = count;
  82169. },
  82170. enumerable: true,
  82171. configurable: true
  82172. });
  82173. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  82174. /**
  82175. * Specifies the number of samples used for the motion blur effect
  82176. * Typically in interval [16, 64]
  82177. */
  82178. get: function () {
  82179. return this._motionBlurSamples;
  82180. },
  82181. set: function (samples) {
  82182. if (this.motionBlurPostProcess) {
  82183. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  82184. }
  82185. this._motionBlurSamples = samples;
  82186. },
  82187. enumerable: true,
  82188. configurable: true
  82189. });
  82190. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  82191. /**
  82192. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  82193. */
  82194. get: function () {
  82195. return this._samples;
  82196. },
  82197. set: function (sampleCount) {
  82198. if (this._samples === sampleCount) {
  82199. return;
  82200. }
  82201. this._samples = sampleCount;
  82202. this._buildPipeline();
  82203. },
  82204. enumerable: true,
  82205. configurable: true
  82206. });
  82207. StandardRenderingPipeline.prototype._buildPipeline = function () {
  82208. var _this = this;
  82209. var ratio = this._ratio;
  82210. var scene = this._scene;
  82211. this._disposePostProcesses();
  82212. this._reset();
  82213. // Create pass post-process
  82214. if (!this._basePostProcess) {
  82215. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  82216. this.originalPostProcess.onApply = function (effect) {
  82217. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  82218. };
  82219. }
  82220. else {
  82221. this.originalPostProcess = this._basePostProcess;
  82222. }
  82223. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  82224. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  82225. }
  82226. this._currentDepthOfFieldSource = this.originalPostProcess;
  82227. if (this._bloomEnabled) {
  82228. // Create down sample X4 post-process
  82229. this._createDownSampleX4PostProcess(scene, ratio / 2);
  82230. // Create bright pass post-process
  82231. this._createBrightPassPostProcess(scene, ratio / 2);
  82232. // Create gaussian blur post-processes (down sampling blurs)
  82233. this._createBlurPostProcesses(scene, ratio / 4, 1);
  82234. // Create texture adder post-process
  82235. this._createTextureAdderPostProcess(scene, ratio);
  82236. // Create depth-of-field source post-process
  82237. 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);
  82238. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  82239. }
  82240. if (this._vlsEnabled) {
  82241. // Create volumetric light
  82242. this._createVolumetricLightPostProcess(scene, ratio);
  82243. // Create volumetric light final post-process
  82244. 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);
  82245. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  82246. }
  82247. if (this._lensFlareEnabled) {
  82248. // Create lens flare post-process
  82249. this._createLensFlarePostProcess(scene, ratio);
  82250. // Create depth-of-field source post-process post lens-flare and disable it now
  82251. 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);
  82252. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  82253. }
  82254. if (this._hdrEnabled) {
  82255. // Create luminance
  82256. this._createLuminancePostProcesses(scene, this._floatTextureType);
  82257. // Create HDR
  82258. this._createHdrPostProcess(scene, ratio);
  82259. // Create depth-of-field source post-process post hdr and disable it now
  82260. 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);
  82261. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  82262. }
  82263. if (this._depthOfFieldEnabled) {
  82264. // Create gaussian blur used by depth-of-field
  82265. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  82266. // Create depth-of-field post-process
  82267. this._createDepthOfFieldPostProcess(scene, ratio);
  82268. }
  82269. if (this._motionBlurEnabled) {
  82270. // Create motion blur post-process
  82271. this._createMotionBlurPostProcess(scene, ratio);
  82272. }
  82273. if (this._fxaaEnabled) {
  82274. // Create fxaa post-process
  82275. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  82277. }
  82278. if (this._cameras !== null) {
  82279. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  82280. }
  82281. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  82282. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  82283. }
  82284. };
  82285. // Down Sample X4 Post-Processs
  82286. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  82287. var _this = this;
  82288. var downSampleX4Offsets = new Array(32);
  82289. 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);
  82290. this.downSampleX4PostProcess.onApply = function (effect) {
  82291. var id = 0;
  82292. var width = _this.downSampleX4PostProcess.width;
  82293. var height = _this.downSampleX4PostProcess.height;
  82294. for (var i = -2; i < 2; i++) {
  82295. for (var j = -2; j < 2; j++) {
  82296. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  82297. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  82298. id += 2;
  82299. }
  82300. }
  82301. effect.setArray2("dsOffsets", downSampleX4Offsets);
  82302. };
  82303. // Add to pipeline
  82304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  82305. };
  82306. // Brightpass Post-Process
  82307. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  82308. var _this = this;
  82309. var brightOffsets = new Array(8);
  82310. 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);
  82311. this.brightPassPostProcess.onApply = function (effect) {
  82312. var sU = (1.0 / _this.brightPassPostProcess.width);
  82313. var sV = (1.0 / _this.brightPassPostProcess.height);
  82314. brightOffsets[0] = -0.5 * sU;
  82315. brightOffsets[1] = 0.5 * sV;
  82316. brightOffsets[2] = 0.5 * sU;
  82317. brightOffsets[3] = 0.5 * sV;
  82318. brightOffsets[4] = -0.5 * sU;
  82319. brightOffsets[5] = -0.5 * sV;
  82320. brightOffsets[6] = 0.5 * sU;
  82321. brightOffsets[7] = -0.5 * sV;
  82322. effect.setArray2("dsOffsets", brightOffsets);
  82323. effect.setFloat("brightThreshold", _this.brightThreshold);
  82324. };
  82325. // Add to pipeline
  82326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  82327. };
  82328. // Create blur H&V post-processes
  82329. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  82330. var _this = this;
  82331. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  82332. var engine = scene.getEngine();
  82333. 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);
  82334. 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);
  82335. blurX.onActivateObservable.add(function () {
  82336. var dw = blurX.width / engine.getRenderWidth();
  82337. blurX.kernel = _this[blurWidthKey] * dw;
  82338. });
  82339. blurY.onActivateObservable.add(function () {
  82340. var dw = blurY.height / engine.getRenderHeight();
  82341. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  82342. });
  82343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  82344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  82345. this.blurHPostProcesses.push(blurX);
  82346. this.blurVPostProcesses.push(blurY);
  82347. };
  82348. // Create texture adder post-process
  82349. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  82350. var _this = this;
  82351. 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);
  82352. this.textureAdderPostProcess.onApply = function (effect) {
  82353. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  82354. effect.setTexture("lensSampler", _this.lensTexture);
  82355. effect.setFloat("exposure", _this.exposure);
  82356. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  82357. };
  82358. // Add to pipeline
  82359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  82360. };
  82361. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  82362. var _this = this;
  82363. var geometryRenderer = scene.enableGeometryBufferRenderer();
  82364. geometryRenderer.enablePosition = true;
  82365. var geometry = geometryRenderer.getGBuffer();
  82366. // Base post-process
  82367. 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));
  82368. var depthValues = BABYLON.Vector2.Zero();
  82369. this.volumetricLightPostProcess.onApply = function (effect) {
  82370. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  82371. var generator = _this.sourceLight.getShadowGenerator();
  82372. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  82373. effect.setTexture("positionSampler", geometry.textures[2]);
  82374. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  82375. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  82376. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  82377. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  82378. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  82379. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  82380. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  82381. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  82382. effect.setVector2("depthValues", depthValues);
  82383. }
  82384. };
  82385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  82386. // Smooth
  82387. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  82388. // Merge
  82389. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  82390. this.volumetricLightMergePostProces.onApply = function (effect) {
  82391. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  82392. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  82393. };
  82394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  82395. };
  82396. // Create luminance
  82397. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  82398. var _this = this;
  82399. // Create luminance
  82400. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  82401. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  82402. var offsets = [];
  82403. this.luminancePostProcess.onApply = function (effect) {
  82404. var sU = (1.0 / _this.luminancePostProcess.width);
  82405. var sV = (1.0 / _this.luminancePostProcess.height);
  82406. offsets[0] = -0.5 * sU;
  82407. offsets[1] = 0.5 * sV;
  82408. offsets[2] = 0.5 * sU;
  82409. offsets[3] = 0.5 * sV;
  82410. offsets[4] = -0.5 * sU;
  82411. offsets[5] = -0.5 * sV;
  82412. offsets[6] = 0.5 * sU;
  82413. offsets[7] = -0.5 * sV;
  82414. effect.setArray2("lumOffsets", offsets);
  82415. };
  82416. // Add to pipeline
  82417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  82418. // Create down sample luminance
  82419. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  82420. var size = Math.pow(3, i);
  82421. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  82422. if (i === 0) {
  82423. defines += "#define FINAL_DOWN_SAMPLER";
  82424. }
  82425. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  82426. this.luminanceDownSamplePostProcesses.push(postProcess);
  82427. }
  82428. // Create callbacks and add effects
  82429. var lastLuminance = this.luminancePostProcess;
  82430. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  82431. var downSampleOffsets = new Array(18);
  82432. pp.onApply = function (effect) {
  82433. if (!lastLuminance) {
  82434. return;
  82435. }
  82436. var id = 0;
  82437. for (var x = -1; x < 2; x++) {
  82438. for (var y = -1; y < 2; y++) {
  82439. downSampleOffsets[id] = x / lastLuminance.width;
  82440. downSampleOffsets[id + 1] = y / lastLuminance.height;
  82441. id += 2;
  82442. }
  82443. }
  82444. effect.setArray2("dsOffsets", downSampleOffsets);
  82445. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  82446. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82447. lastLuminance = _this.luminancePostProcess;
  82448. }
  82449. else {
  82450. lastLuminance = pp;
  82451. }
  82452. };
  82453. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  82454. pp.onAfterRender = function (effect) {
  82455. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  82456. 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);
  82457. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  82458. };
  82459. }
  82460. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  82461. });
  82462. };
  82463. // Create HDR post-process
  82464. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  82465. var _this = this;
  82466. 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);
  82467. var outputLiminance = 1;
  82468. var time = 0;
  82469. var lastTime = 0;
  82470. this.hdrPostProcess.onApply = function (effect) {
  82471. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  82472. time += scene.getEngine().getDeltaTime();
  82473. if (outputLiminance < 0) {
  82474. outputLiminance = _this._hdrCurrentLuminance;
  82475. }
  82476. else {
  82477. var dt = (lastTime - time) / 1000.0;
  82478. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  82479. outputLiminance += _this.hdrDecreaseRate * dt;
  82480. }
  82481. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  82482. outputLiminance -= _this.hdrIncreaseRate * dt;
  82483. }
  82484. else {
  82485. outputLiminance = _this._hdrCurrentLuminance;
  82486. }
  82487. }
  82488. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  82489. effect.setFloat("averageLuminance", outputLiminance);
  82490. lastTime = time;
  82491. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  82492. };
  82493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  82494. };
  82495. // Create lens flare post-process
  82496. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  82497. var _this = this;
  82498. 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);
  82499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  82500. this._createBlurPostProcesses(scene, ratio / 4, 2);
  82501. 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);
  82502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  82503. var resolution = new BABYLON.Vector2(0, 0);
  82504. // Lens flare
  82505. this.lensFlarePostProcess.onApply = function (effect) {
  82506. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  82507. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  82508. effect.setFloat("strength", _this.lensFlareStrength);
  82509. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  82510. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  82511. // Shift
  82512. resolution.x = _this.lensFlarePostProcess.width;
  82513. resolution.y = _this.lensFlarePostProcess.height;
  82514. effect.setVector2("resolution", resolution);
  82515. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  82516. };
  82517. // Compose
  82518. 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);
  82519. 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);
  82520. this.lensFlareComposePostProcess.onApply = function (effect) {
  82521. if (!_this._scene.activeCamera) {
  82522. return;
  82523. }
  82524. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82525. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  82526. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  82527. // Lens start rotation matrix
  82528. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  82529. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  82530. 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));
  82531. camRot *= 4.0;
  82532. 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);
  82533. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  82534. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  82535. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  82536. };
  82537. };
  82538. // Create depth-of-field post-process
  82539. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  82540. var _this = this;
  82541. 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);
  82542. this.depthOfFieldPostProcess.onApply = function (effect) {
  82543. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  82544. effect.setTexture("depthSampler", _this._getDepthTexture());
  82545. effect.setFloat("distance", _this.depthOfFieldDistance);
  82546. };
  82547. // Add to pipeline
  82548. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  82549. };
  82550. // Create motion blur post-process
  82551. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  82552. var _this = this;
  82553. 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);
  82554. var motionScale = 0;
  82555. var prevViewProjection = BABYLON.Matrix.Identity();
  82556. var invViewProjection = BABYLON.Matrix.Identity();
  82557. var viewProjection = BABYLON.Matrix.Identity();
  82558. var screenSize = BABYLON.Vector2.Zero();
  82559. this.motionBlurPostProcess.onApply = function (effect) {
  82560. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  82561. viewProjection.invertToRef(invViewProjection);
  82562. effect.setMatrix("inverseViewProjection", invViewProjection);
  82563. effect.setMatrix("prevViewProjection", prevViewProjection);
  82564. prevViewProjection = viewProjection;
  82565. screenSize.x = _this.motionBlurPostProcess.width;
  82566. screenSize.y = _this.motionBlurPostProcess.height;
  82567. effect.setVector2("screenSize", screenSize);
  82568. motionScale = scene.getEngine().getFps() / 60.0;
  82569. effect.setFloat("motionScale", motionScale);
  82570. effect.setFloat("motionStrength", _this.motionStrength);
  82571. effect.setTexture("depthSampler", _this._getDepthTexture());
  82572. };
  82573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  82574. };
  82575. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  82576. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  82577. var renderer = this._scene.enableGeometryBufferRenderer();
  82578. return renderer.getGBuffer().textures[0];
  82579. }
  82580. return this._scene.enableDepthRenderer().getDepthMap();
  82581. };
  82582. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  82583. for (var i = 0; i < this._cameras.length; i++) {
  82584. var camera = this._cameras[i];
  82585. if (this.originalPostProcess) {
  82586. this.originalPostProcess.dispose(camera);
  82587. }
  82588. if (this.downSampleX4PostProcess) {
  82589. this.downSampleX4PostProcess.dispose(camera);
  82590. }
  82591. if (this.brightPassPostProcess) {
  82592. this.brightPassPostProcess.dispose(camera);
  82593. }
  82594. if (this.textureAdderPostProcess) {
  82595. this.textureAdderPostProcess.dispose(camera);
  82596. }
  82597. if (this.textureAdderFinalPostProcess) {
  82598. this.textureAdderFinalPostProcess.dispose(camera);
  82599. }
  82600. if (this.volumetricLightPostProcess) {
  82601. this.volumetricLightPostProcess.dispose(camera);
  82602. }
  82603. if (this.volumetricLightSmoothXPostProcess) {
  82604. this.volumetricLightSmoothXPostProcess.dispose(camera);
  82605. }
  82606. if (this.volumetricLightSmoothYPostProcess) {
  82607. this.volumetricLightSmoothYPostProcess.dispose(camera);
  82608. }
  82609. if (this.volumetricLightMergePostProces) {
  82610. this.volumetricLightMergePostProces.dispose(camera);
  82611. }
  82612. if (this.volumetricLightFinalPostProcess) {
  82613. this.volumetricLightFinalPostProcess.dispose(camera);
  82614. }
  82615. if (this.lensFlarePostProcess) {
  82616. this.lensFlarePostProcess.dispose(camera);
  82617. }
  82618. if (this.lensFlareComposePostProcess) {
  82619. this.lensFlareComposePostProcess.dispose(camera);
  82620. }
  82621. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  82622. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  82623. }
  82624. if (this.luminancePostProcess) {
  82625. this.luminancePostProcess.dispose(camera);
  82626. }
  82627. if (this.hdrPostProcess) {
  82628. this.hdrPostProcess.dispose(camera);
  82629. }
  82630. if (this.hdrFinalPostProcess) {
  82631. this.hdrFinalPostProcess.dispose(camera);
  82632. }
  82633. if (this.depthOfFieldPostProcess) {
  82634. this.depthOfFieldPostProcess.dispose(camera);
  82635. }
  82636. if (this.motionBlurPostProcess) {
  82637. this.motionBlurPostProcess.dispose(camera);
  82638. }
  82639. if (this.fxaaPostProcess) {
  82640. this.fxaaPostProcess.dispose(camera);
  82641. }
  82642. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  82643. this.blurHPostProcesses[j].dispose(camera);
  82644. }
  82645. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  82646. this.blurVPostProcesses[j].dispose(camera);
  82647. }
  82648. }
  82649. this.originalPostProcess = null;
  82650. this.downSampleX4PostProcess = null;
  82651. this.brightPassPostProcess = null;
  82652. this.textureAdderPostProcess = null;
  82653. this.textureAdderFinalPostProcess = null;
  82654. this.volumetricLightPostProcess = null;
  82655. this.volumetricLightSmoothXPostProcess = null;
  82656. this.volumetricLightSmoothYPostProcess = null;
  82657. this.volumetricLightMergePostProces = null;
  82658. this.volumetricLightFinalPostProcess = null;
  82659. this.lensFlarePostProcess = null;
  82660. this.lensFlareComposePostProcess = null;
  82661. this.luminancePostProcess = null;
  82662. this.hdrPostProcess = null;
  82663. this.hdrFinalPostProcess = null;
  82664. this.depthOfFieldPostProcess = null;
  82665. this.motionBlurPostProcess = null;
  82666. this.fxaaPostProcess = null;
  82667. this.luminanceDownSamplePostProcesses = [];
  82668. this.blurHPostProcesses = [];
  82669. this.blurVPostProcesses = [];
  82670. };
  82671. /**
  82672. * Dispose of the pipeline and stop all post processes
  82673. */
  82674. StandardRenderingPipeline.prototype.dispose = function () {
  82675. this._disposePostProcesses();
  82676. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  82677. _super.prototype.dispose.call(this);
  82678. };
  82679. /**
  82680. * Serialize the rendering pipeline (Used when exporting)
  82681. * @returns the serialized object
  82682. */
  82683. StandardRenderingPipeline.prototype.serialize = function () {
  82684. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82685. if (this.sourceLight) {
  82686. serializationObject.sourceLightId = this.sourceLight.id;
  82687. }
  82688. serializationObject.customType = "StandardRenderingPipeline";
  82689. return serializationObject;
  82690. };
  82691. /**
  82692. * Parse the serialized pipeline
  82693. * @param source Source pipeline.
  82694. * @param scene The scene to load the pipeline to.
  82695. * @param rootUrl The URL of the serialized pipeline.
  82696. * @returns An instantiated pipeline from the serialized object.
  82697. */
  82698. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  82699. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  82700. if (source.sourceLightId) {
  82701. p.sourceLight = scene.getLightByID(source.sourceLightId);
  82702. }
  82703. return p;
  82704. };
  82705. // Luminance steps
  82706. StandardRenderingPipeline.LuminanceSteps = 6;
  82707. __decorate([
  82708. BABYLON.serialize()
  82709. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  82710. __decorate([
  82711. BABYLON.serialize()
  82712. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  82713. __decorate([
  82714. BABYLON.serialize()
  82715. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  82716. __decorate([
  82717. BABYLON.serialize()
  82718. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  82719. __decorate([
  82720. BABYLON.serializeAsTexture("lensTexture")
  82721. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  82722. __decorate([
  82723. BABYLON.serialize()
  82724. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  82725. __decorate([
  82726. BABYLON.serialize()
  82727. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  82728. __decorate([
  82729. BABYLON.serialize()
  82730. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  82731. __decorate([
  82732. BABYLON.serialize()
  82733. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  82734. __decorate([
  82735. BABYLON.serialize()
  82736. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  82737. __decorate([
  82738. BABYLON.serialize()
  82739. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  82740. __decorate([
  82741. BABYLON.serializeAsTexture("lensColorTexture")
  82742. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  82743. __decorate([
  82744. BABYLON.serialize()
  82745. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  82746. __decorate([
  82747. BABYLON.serialize()
  82748. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  82749. __decorate([
  82750. BABYLON.serialize()
  82751. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  82752. __decorate([
  82753. BABYLON.serialize()
  82754. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  82755. __decorate([
  82756. BABYLON.serializeAsTexture("lensStarTexture")
  82757. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  82758. __decorate([
  82759. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  82760. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  82761. __decorate([
  82762. BABYLON.serialize()
  82763. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  82764. __decorate([
  82765. BABYLON.serialize()
  82766. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  82767. __decorate([
  82768. BABYLON.serialize()
  82769. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  82770. __decorate([
  82771. BABYLON.serialize()
  82772. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  82773. __decorate([
  82774. BABYLON.serialize()
  82775. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  82776. __decorate([
  82777. BABYLON.serialize()
  82778. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  82779. __decorate([
  82780. BABYLON.serialize()
  82781. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  82782. __decorate([
  82783. BABYLON.serialize()
  82784. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  82785. __decorate([
  82786. BABYLON.serialize()
  82787. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  82788. __decorate([
  82789. BABYLON.serialize()
  82790. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  82791. __decorate([
  82792. BABYLON.serialize()
  82793. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  82794. __decorate([
  82795. BABYLON.serialize()
  82796. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  82797. __decorate([
  82798. BABYLON.serialize()
  82799. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  82800. __decorate([
  82801. BABYLON.serialize()
  82802. ], StandardRenderingPipeline.prototype, "samples", null);
  82803. return StandardRenderingPipeline;
  82804. }(BABYLON.PostProcessRenderPipeline));
  82805. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  82806. })(BABYLON || (BABYLON = {}));
  82807. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  82808. var BABYLON;
  82809. (function (BABYLON) {
  82810. var FxaaPostProcess = /** @class */ (function (_super) {
  82811. __extends(FxaaPostProcess, _super);
  82812. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  82813. if (camera === void 0) { camera = null; }
  82814. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82815. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  82816. var defines = _this._getDefines();
  82817. _this.updateEffect(defines);
  82818. _this.onApplyObservable.add(function (effect) {
  82819. var texelSize = _this.texelSize;
  82820. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  82821. });
  82822. return _this;
  82823. }
  82824. FxaaPostProcess.prototype._getDefines = function () {
  82825. var engine = this.getEngine();
  82826. if (!engine) {
  82827. return null;
  82828. }
  82829. var glInfo = engine.getGlInfo();
  82830. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  82831. return "#define MALI 1\n";
  82832. }
  82833. return null;
  82834. };
  82835. return FxaaPostProcess;
  82836. }(BABYLON.PostProcess));
  82837. BABYLON.FxaaPostProcess = FxaaPostProcess;
  82838. })(BABYLON || (BABYLON = {}));
  82839. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  82840. var BABYLON;
  82841. (function (BABYLON) {
  82842. /**
  82843. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  82844. */
  82845. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  82846. __extends(ChromaticAberrationPostProcess, _super);
  82847. /**
  82848. * Creates a new instance ChromaticAberrationPostProcess
  82849. * @param name The name of the effect.
  82850. * @param screenWidth The width of the screen to apply the effect on.
  82851. * @param screenHeight The height of the screen to apply the effect on.
  82852. * @param options The required width/height ratio to downsize to before computing the render pass.
  82853. * @param camera The camera to apply the render pass to.
  82854. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82855. * @param engine The engine which the post process will be applied. (default: current engine)
  82856. * @param reusable If the post process can be reused on the same frame. (default: false)
  82857. * @param textureType Type of textures used when performing the post process. (default: 0)
  82858. * @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)
  82859. */
  82860. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82861. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82862. if (blockCompilation === void 0) { blockCompilation = false; }
  82863. 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;
  82864. /**
  82865. * The amount of seperation of rgb channels (default: 30)
  82866. */
  82867. _this.aberrationAmount = 30;
  82868. /**
  82869. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  82870. */
  82871. _this.radialIntensity = 0;
  82872. /**
  82873. * 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))
  82874. */
  82875. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  82876. /**
  82877. * 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))
  82878. */
  82879. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  82880. _this.onApplyObservable.add(function (effect) {
  82881. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  82882. effect.setFloat('screen_width', screenWidth);
  82883. effect.setFloat('screen_height', screenHeight);
  82884. effect.setFloat('radialIntensity', _this.radialIntensity);
  82885. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  82886. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  82887. });
  82888. return _this;
  82889. }
  82890. return ChromaticAberrationPostProcess;
  82891. }(BABYLON.PostProcess));
  82892. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  82893. })(BABYLON || (BABYLON = {}));
  82894. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  82895. var BABYLON;
  82896. (function (BABYLON) {
  82897. /**
  82898. * The GrainPostProcess adds noise to the image at mid luminance levels
  82899. */
  82900. var GrainPostProcess = /** @class */ (function (_super) {
  82901. __extends(GrainPostProcess, _super);
  82902. /**
  82903. * Creates a new instance of @see GrainPostProcess
  82904. * @param name The name of the effect.
  82905. * @param options The required width/height ratio to downsize to before computing the render pass.
  82906. * @param camera The camera to apply the render pass to.
  82907. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82908. * @param engine The engine which the post process will be applied. (default: current engine)
  82909. * @param reusable If the post process can be reused on the same frame. (default: false)
  82910. * @param textureType Type of textures used when performing the post process. (default: 0)
  82911. * @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)
  82912. */
  82913. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82914. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82915. if (blockCompilation === void 0) { blockCompilation = false; }
  82916. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82917. /**
  82918. * The intensity of the grain added (default: 30)
  82919. */
  82920. _this.intensity = 30;
  82921. /**
  82922. * If the grain should be randomized on every frame
  82923. */
  82924. _this.animated = false;
  82925. _this.onApplyObservable.add(function (effect) {
  82926. effect.setFloat('intensity', _this.intensity);
  82927. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  82928. });
  82929. return _this;
  82930. }
  82931. return GrainPostProcess;
  82932. }(BABYLON.PostProcess));
  82933. BABYLON.GrainPostProcess = GrainPostProcess;
  82934. })(BABYLON || (BABYLON = {}));
  82935. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82936. var BABYLON;
  82937. (function (BABYLON) {
  82938. /**
  82939. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82940. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82941. */
  82942. var SharpenPostProcess = /** @class */ (function (_super) {
  82943. __extends(SharpenPostProcess, _super);
  82944. /**
  82945. * Creates a new instance ConvolutionPostProcess
  82946. * @param name The name of the effect.
  82947. * @param options The required width/height ratio to downsize to before computing the render pass.
  82948. * @param camera The camera to apply the render pass to.
  82949. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82950. * @param engine The engine which the post process will be applied. (default: current engine)
  82951. * @param reusable If the post process can be reused on the same frame. (default: false)
  82952. * @param textureType Type of textures used when performing the post process. (default: 0)
  82953. * @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)
  82954. */
  82955. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82956. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82957. if (blockCompilation === void 0) { blockCompilation = false; }
  82958. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82959. /**
  82960. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82961. */
  82962. _this.colorAmount = 1.0;
  82963. /**
  82964. * How much sharpness should be applied (default: 0.3)
  82965. */
  82966. _this.edgeAmount = 0.3;
  82967. _this.onApply = function (effect) {
  82968. effect.setFloat2("screenSize", _this.width, _this.height);
  82969. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82970. };
  82971. return _this;
  82972. }
  82973. return SharpenPostProcess;
  82974. }(BABYLON.PostProcess));
  82975. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82976. })(BABYLON || (BABYLON = {}));
  82977. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82978. var BABYLON;
  82979. (function (BABYLON) {
  82980. /**
  82981. * The Blur Post Process which blurs an image based on a kernel and direction.
  82982. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82983. */
  82984. var BlurPostProcess = /** @class */ (function (_super) {
  82985. __extends(BlurPostProcess, _super);
  82986. /**
  82987. * Creates a new instance BlurPostProcess
  82988. * @param name The name of the effect.
  82989. * @param direction The direction in which to blur the image.
  82990. * @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.
  82991. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82992. * @param camera The camera to apply the render pass to.
  82993. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82994. * @param engine The engine which the post process will be applied. (default: current engine)
  82995. * @param reusable If the post process can be reused on the same frame. (default: false)
  82996. * @param textureType Type of textures used when performing the post process. (default: 0)
  82997. * @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)
  82998. */
  82999. function BlurPostProcess(name,
  83000. /** The direction in which to blur the image. */
  83001. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  83002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83003. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83004. if (defines === void 0) { defines = ""; }
  83005. if (blockCompilation === void 0) { blockCompilation = false; }
  83006. 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;
  83007. _this.direction = direction;
  83008. _this.blockCompilation = blockCompilation;
  83009. _this._packedFloat = false;
  83010. _this._staticDefines = "";
  83011. _this._staticDefines = defines;
  83012. _this.onApplyObservable.add(function (effect) {
  83013. if (_this._outputTexture) {
  83014. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  83015. }
  83016. else {
  83017. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  83018. }
  83019. });
  83020. _this.kernel = kernel;
  83021. return _this;
  83022. }
  83023. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  83024. /**
  83025. * Gets the length in pixels of the blur sample region
  83026. */
  83027. get: function () {
  83028. return this._idealKernel;
  83029. },
  83030. /**
  83031. * Sets the length in pixels of the blur sample region
  83032. */
  83033. set: function (v) {
  83034. if (this._idealKernel === v) {
  83035. return;
  83036. }
  83037. v = Math.max(v, 1);
  83038. this._idealKernel = v;
  83039. this._kernel = this._nearestBestKernel(v);
  83040. if (!this.blockCompilation) {
  83041. this._updateParameters();
  83042. }
  83043. },
  83044. enumerable: true,
  83045. configurable: true
  83046. });
  83047. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  83048. /**
  83049. * Gets wether or not the blur is unpacking/repacking floats
  83050. */
  83051. get: function () {
  83052. return this._packedFloat;
  83053. },
  83054. /**
  83055. * Sets wether or not the blur needs to unpack/repack floats
  83056. */
  83057. set: function (v) {
  83058. if (this._packedFloat === v) {
  83059. return;
  83060. }
  83061. this._packedFloat = v;
  83062. if (!this.blockCompilation) {
  83063. this._updateParameters();
  83064. }
  83065. },
  83066. enumerable: true,
  83067. configurable: true
  83068. });
  83069. /**
  83070. * Updates the effect with the current post process compile time values and recompiles the shader.
  83071. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83072. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83073. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83074. * @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
  83075. * @param onCompiled Called when the shader has been compiled.
  83076. * @param onError Called if there is an error when compiling a shader.
  83077. */
  83078. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83079. if (defines === void 0) { defines = null; }
  83080. if (uniforms === void 0) { uniforms = null; }
  83081. if (samplers === void 0) { samplers = null; }
  83082. this._updateParameters(onCompiled, onError);
  83083. };
  83084. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  83085. // Generate sampling offsets and weights
  83086. var N = this._kernel;
  83087. var centerIndex = (N - 1) / 2;
  83088. // Generate Gaussian sampling weights over kernel
  83089. var offsets = [];
  83090. var weights = [];
  83091. var totalWeight = 0;
  83092. for (var i = 0; i < N; i++) {
  83093. var u = i / (N - 1);
  83094. var w = this._gaussianWeight(u * 2.0 - 1);
  83095. offsets[i] = (i - centerIndex);
  83096. weights[i] = w;
  83097. totalWeight += w;
  83098. }
  83099. // Normalize weights
  83100. for (var i = 0; i < weights.length; i++) {
  83101. weights[i] /= totalWeight;
  83102. }
  83103. // Optimize: combine samples to take advantage of hardware linear sampling
  83104. // Walk from left to center, combining pairs (symmetrically)
  83105. var linearSamplingWeights = [];
  83106. var linearSamplingOffsets = [];
  83107. var linearSamplingMap = [];
  83108. for (var i = 0; i <= centerIndex; i += 2) {
  83109. var j = Math.min(i + 1, Math.floor(centerIndex));
  83110. var singleCenterSample = i === j;
  83111. if (singleCenterSample) {
  83112. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83113. }
  83114. else {
  83115. var sharedCell = j === centerIndex;
  83116. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  83117. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  83118. if (offsetLinear === 0) {
  83119. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  83120. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  83121. }
  83122. else {
  83123. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  83124. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  83125. }
  83126. }
  83127. }
  83128. for (var i = 0; i < linearSamplingMap.length; i++) {
  83129. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  83130. linearSamplingWeights[i] = linearSamplingMap[i].w;
  83131. }
  83132. // Replace with optimized
  83133. offsets = linearSamplingOffsets;
  83134. weights = linearSamplingWeights;
  83135. // Generate shaders
  83136. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  83137. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  83138. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  83139. var defines = "";
  83140. defines += this._staticDefines;
  83141. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  83142. if (this._staticDefines.indexOf("DOF") != -1) {
  83143. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  83144. varyingCount--;
  83145. }
  83146. for (var i = 0; i < varyingCount; i++) {
  83147. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  83148. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  83149. }
  83150. var depCount = 0;
  83151. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  83152. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  83153. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  83154. depCount++;
  83155. }
  83156. if (this.packedFloat) {
  83157. defines += "#define PACKEDFLOAT 1";
  83158. }
  83159. this.blockCompilation = false;
  83160. _super.prototype.updateEffect.call(this, defines, null, null, {
  83161. varyingCount: varyingCount,
  83162. depCount: depCount
  83163. }, onCompiled, onError);
  83164. };
  83165. /**
  83166. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  83167. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  83168. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  83169. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  83170. * The gaps between physical kernels are compensated for in the weighting of the samples
  83171. * @param idealKernel Ideal blur kernel.
  83172. * @return Nearest best kernel.
  83173. */
  83174. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  83175. var v = Math.round(idealKernel);
  83176. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  83177. var k = _a[_i];
  83178. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  83179. return Math.max(k, 3);
  83180. }
  83181. }
  83182. return Math.max(v, 3);
  83183. };
  83184. /**
  83185. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  83186. * @param x The point on the Gaussian distribution to sample.
  83187. * @return the value of the Gaussian function at x.
  83188. */
  83189. BlurPostProcess.prototype._gaussianWeight = function (x) {
  83190. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  83191. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  83192. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  83193. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  83194. // truncated at around 1.3% of peak strength.
  83195. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  83196. var sigma = (1 / 3);
  83197. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  83198. var exponent = -((x * x) / (2.0 * sigma * sigma));
  83199. var weight = (1.0 / denominator) * Math.exp(exponent);
  83200. return weight;
  83201. };
  83202. /**
  83203. * Generates a string that can be used as a floating point number in GLSL.
  83204. * @param x Value to print.
  83205. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  83206. * @return GLSL float string.
  83207. */
  83208. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  83209. if (decimalFigures === void 0) { decimalFigures = 8; }
  83210. return x.toFixed(decimalFigures).replace(/0+$/, '');
  83211. };
  83212. return BlurPostProcess;
  83213. }(BABYLON.PostProcess));
  83214. BABYLON.BlurPostProcess = BlurPostProcess;
  83215. })(BABYLON || (BABYLON = {}));
  83216. //# sourceMappingURL=babylon.blurPostProcess.js.map
  83217. var BABYLON;
  83218. (function (BABYLON) {
  83219. /**
  83220. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  83221. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  83222. * based on samples that have a large difference in distance than the center pixel.
  83223. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83224. */
  83225. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  83226. __extends(DepthOfFieldBlurPostProcess, _super);
  83227. /**
  83228. * Creates a new instance CircleOfConfusionPostProcess
  83229. * @param name The name of the effect.
  83230. * @param scene The scene the effect belongs to.
  83231. * @param direction The direction the blur should be applied.
  83232. * @param kernel The size of the kernel used to blur.
  83233. * @param options The required width/height ratio to downsize to before computing the render pass.
  83234. * @param camera The camera to apply the render pass to.
  83235. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  83236. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  83237. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83238. * @param engine The engine which the post process will be applied. (default: current engine)
  83239. * @param reusable If the post process can be reused on the same frame. (default: false)
  83240. * @param textureType Type of textures used when performing the post process. (default: 0)
  83241. * @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)
  83242. */
  83243. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  83244. if (imageToBlur === void 0) { imageToBlur = null; }
  83245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83246. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83247. if (blockCompilation === void 0) { blockCompilation = false; }
  83248. 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;
  83249. _this.direction = direction;
  83250. _this.onApplyObservable.add(function (effect) {
  83251. if (imageToBlur != null) {
  83252. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  83253. }
  83254. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83255. if (scene.activeCamera) {
  83256. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  83257. }
  83258. });
  83259. return _this;
  83260. }
  83261. return DepthOfFieldBlurPostProcess;
  83262. }(BABYLON.BlurPostProcess));
  83263. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  83264. })(BABYLON || (BABYLON = {}));
  83265. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  83266. var BABYLON;
  83267. (function (BABYLON) {
  83268. /**
  83269. * Options to be set when merging outputs from the default pipeline.
  83270. */
  83271. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  83272. function DepthOfFieldMergePostProcessOptions() {
  83273. }
  83274. return DepthOfFieldMergePostProcessOptions;
  83275. }());
  83276. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  83277. /**
  83278. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83279. */
  83280. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  83281. __extends(DepthOfFieldMergePostProcess, _super);
  83282. /**
  83283. * Creates a new instance of DepthOfFieldMergePostProcess
  83284. * @param name The name of the effect.
  83285. * @param originalFromInput Post process which's input will be used for the merge.
  83286. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  83287. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  83288. * @param options The required width/height ratio to downsize to before computing the render pass.
  83289. * @param camera The camera to apply the render pass to.
  83290. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83291. * @param engine The engine which the post process will be applied. (default: current engine)
  83292. * @param reusable If the post process can be reused on the same frame. (default: false)
  83293. * @param textureType Type of textures used when performing the post process. (default: 0)
  83294. * @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)
  83295. */
  83296. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83297. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83298. if (blockCompilation === void 0) { blockCompilation = false; }
  83299. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83300. _this.blurSteps = blurSteps;
  83301. _this.onApplyObservable.add(function (effect) {
  83302. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83303. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  83304. blurSteps.forEach(function (step, index) {
  83305. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  83306. });
  83307. });
  83308. if (!blockCompilation) {
  83309. _this.updateEffect();
  83310. }
  83311. return _this;
  83312. }
  83313. /**
  83314. * Updates the effect with the current post process compile time values and recompiles the shader.
  83315. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  83316. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  83317. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  83318. * @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
  83319. * @param onCompiled Called when the shader has been compiled.
  83320. * @param onError Called if there is an error when compiling a shader.
  83321. */
  83322. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  83323. if (defines === void 0) { defines = null; }
  83324. if (uniforms === void 0) { uniforms = null; }
  83325. if (samplers === void 0) { samplers = null; }
  83326. if (!defines) {
  83327. defines = "";
  83328. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  83329. }
  83330. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  83331. };
  83332. return DepthOfFieldMergePostProcess;
  83333. }(BABYLON.PostProcess));
  83334. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  83335. })(BABYLON || (BABYLON = {}));
  83336. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  83337. var BABYLON;
  83338. (function (BABYLON) {
  83339. /**
  83340. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  83341. */
  83342. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  83343. __extends(CircleOfConfusionPostProcess, _super);
  83344. /**
  83345. * Creates a new instance CircleOfConfusionPostProcess
  83346. * @param name The name of the effect.
  83347. * @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.
  83348. * @param options The required width/height ratio to downsize to before computing the render pass.
  83349. * @param camera The camera to apply the render pass to.
  83350. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83351. * @param engine The engine which the post process will be applied. (default: current engine)
  83352. * @param reusable If the post process can be reused on the same frame. (default: false)
  83353. * @param textureType Type of textures used when performing the post process. (default: 0)
  83354. * @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)
  83355. */
  83356. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83357. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83358. if (blockCompilation === void 0) { blockCompilation = false; }
  83359. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83360. /**
  83361. * 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.
  83362. */
  83363. _this.lensSize = 50;
  83364. /**
  83365. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83366. */
  83367. _this.fStop = 1.4;
  83368. /**
  83369. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83370. */
  83371. _this.focusDistance = 2000;
  83372. /**
  83373. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  83374. */
  83375. _this.focalLength = 50;
  83376. _this._depthTexture = null;
  83377. _this._depthTexture = depthTexture;
  83378. _this.onApplyObservable.add(function (effect) {
  83379. if (!_this._depthTexture) {
  83380. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  83381. return;
  83382. }
  83383. effect.setTexture("depthSampler", _this._depthTexture);
  83384. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  83385. var aperture = _this.lensSize / _this.fStop;
  83386. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  83387. effect.setFloat('focusDistance', _this.focusDistance);
  83388. effect.setFloat('cocPrecalculation', cocPrecalculation);
  83389. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  83390. });
  83391. return _this;
  83392. }
  83393. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  83394. /**
  83395. * 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.
  83396. */
  83397. set: function (value) {
  83398. this._depthTexture = value;
  83399. },
  83400. enumerable: true,
  83401. configurable: true
  83402. });
  83403. return CircleOfConfusionPostProcess;
  83404. }(BABYLON.PostProcess));
  83405. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  83406. })(BABYLON || (BABYLON = {}));
  83407. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  83408. var BABYLON;
  83409. (function (BABYLON) {
  83410. /**
  83411. * Specifies the level of max blur that should be applied when using the depth of field effect
  83412. */
  83413. var DepthOfFieldEffectBlurLevel;
  83414. (function (DepthOfFieldEffectBlurLevel) {
  83415. /**
  83416. * Subtle blur
  83417. */
  83418. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  83419. /**
  83420. * Medium blur
  83421. */
  83422. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  83423. /**
  83424. * Large blur
  83425. */
  83426. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  83427. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  83428. ;
  83429. /**
  83430. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  83431. */
  83432. var DepthOfFieldEffect = /** @class */ (function (_super) {
  83433. __extends(DepthOfFieldEffect, _super);
  83434. /**
  83435. * Creates a new instance DepthOfFieldEffect
  83436. * @param scene The scene the effect belongs to.
  83437. * @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.
  83438. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83439. * @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)
  83440. */
  83441. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  83442. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  83443. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83444. if (blockCompilation === void 0) { blockCompilation = false; }
  83445. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  83446. return _this._effects;
  83447. }, true) || this;
  83448. /**
  83449. * @hidden Internal post processes in depth of field effect
  83450. */
  83451. _this._effects = [];
  83452. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  83453. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83454. // 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)
  83455. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  83456. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  83457. _this._depthOfFieldBlurY = [];
  83458. _this._depthOfFieldBlurX = [];
  83459. var blurCount = 1;
  83460. var kernelSize = 15;
  83461. switch (blurLevel) {
  83462. case DepthOfFieldEffectBlurLevel.High: {
  83463. blurCount = 3;
  83464. kernelSize = 51;
  83465. break;
  83466. }
  83467. case DepthOfFieldEffectBlurLevel.Medium: {
  83468. blurCount = 2;
  83469. kernelSize = 31;
  83470. break;
  83471. }
  83472. default: {
  83473. kernelSize = 15;
  83474. blurCount = 1;
  83475. break;
  83476. }
  83477. }
  83478. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  83479. var ratio = 1.0;
  83480. for (var i = 0; i < blurCount; i++) {
  83481. 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);
  83482. blurY.autoClear = false;
  83483. ratio = 0.75 / Math.pow(2, i);
  83484. 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);
  83485. blurX.autoClear = false;
  83486. _this._depthOfFieldBlurY.push(blurY);
  83487. _this._depthOfFieldBlurX.push(blurX);
  83488. }
  83489. // Set all post processes on the effect.
  83490. _this._effects = [_this._circleOfConfusion];
  83491. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  83492. _this._effects.push(_this._depthOfFieldBlurY[i]);
  83493. _this._effects.push(_this._depthOfFieldBlurX[i]);
  83494. }
  83495. // Merge blurred images with original image based on circleOfConfusion
  83496. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83497. _this._dofMerge.autoClear = false;
  83498. _this._effects.push(_this._dofMerge);
  83499. return _this;
  83500. }
  83501. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  83502. get: function () {
  83503. return this._circleOfConfusion.focalLength;
  83504. },
  83505. /**
  83506. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  83507. */
  83508. set: function (value) {
  83509. this._circleOfConfusion.focalLength = value;
  83510. },
  83511. enumerable: true,
  83512. configurable: true
  83513. });
  83514. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  83515. get: function () {
  83516. return this._circleOfConfusion.fStop;
  83517. },
  83518. /**
  83519. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  83520. */
  83521. set: function (value) {
  83522. this._circleOfConfusion.fStop = value;
  83523. },
  83524. enumerable: true,
  83525. configurable: true
  83526. });
  83527. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  83528. get: function () {
  83529. return this._circleOfConfusion.focusDistance;
  83530. },
  83531. /**
  83532. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  83533. */
  83534. set: function (value) {
  83535. this._circleOfConfusion.focusDistance = value;
  83536. },
  83537. enumerable: true,
  83538. configurable: true
  83539. });
  83540. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  83541. get: function () {
  83542. return this._circleOfConfusion.lensSize;
  83543. },
  83544. /**
  83545. * 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.
  83546. */
  83547. set: function (value) {
  83548. this._circleOfConfusion.lensSize = value;
  83549. },
  83550. enumerable: true,
  83551. configurable: true
  83552. });
  83553. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  83554. /**
  83555. * 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.
  83556. */
  83557. set: function (value) {
  83558. this._circleOfConfusion.depthTexture = value;
  83559. },
  83560. enumerable: true,
  83561. configurable: true
  83562. });
  83563. /**
  83564. * Disposes each of the internal effects for a given camera.
  83565. * @param camera The camera to dispose the effect on.
  83566. */
  83567. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  83568. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83569. this._effects[effectIndex].dispose(camera);
  83570. }
  83571. };
  83572. /**
  83573. * @hidden Internal
  83574. */
  83575. DepthOfFieldEffect.prototype._updateEffects = function () {
  83576. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83577. this._effects[effectIndex].updateEffect();
  83578. }
  83579. };
  83580. /**
  83581. * Internal
  83582. * @returns if all the contained post processes are ready.
  83583. * @hidden
  83584. */
  83585. DepthOfFieldEffect.prototype._isReady = function () {
  83586. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83587. if (!this._effects[effectIndex].isReady()) {
  83588. return false;
  83589. }
  83590. }
  83591. return true;
  83592. };
  83593. return DepthOfFieldEffect;
  83594. }(BABYLON.PostProcessRenderEffect));
  83595. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  83596. })(BABYLON || (BABYLON = {}));
  83597. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  83598. var BABYLON;
  83599. (function (BABYLON) {
  83600. /**
  83601. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  83602. */
  83603. var BloomMergePostProcess = /** @class */ (function (_super) {
  83604. __extends(BloomMergePostProcess, _super);
  83605. /**
  83606. * Creates a new instance of @see BloomMergePostProcess
  83607. * @param name The name of the effect.
  83608. * @param originalFromInput Post process which's input will be used for the merge.
  83609. * @param blurred Blurred highlights post process which's output will be used.
  83610. * @param weight Weight of the bloom to be added to the original input.
  83611. * @param options The required width/height ratio to downsize to before computing the render pass.
  83612. * @param camera The camera to apply the render pass to.
  83613. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  83614. * @param engine The engine which the post process will be applied. (default: current engine)
  83615. * @param reusable If the post process can be reused on the same frame. (default: false)
  83616. * @param textureType Type of textures used when performing the post process. (default: 0)
  83617. * @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)
  83618. */
  83619. function BloomMergePostProcess(name, originalFromInput, blurred,
  83620. /** Weight of the bloom to be added to the original input. */
  83621. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83622. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83623. if (blockCompilation === void 0) { blockCompilation = false; }
  83624. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  83625. _this.weight = weight;
  83626. _this.onApplyObservable.add(function (effect) {
  83627. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  83628. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  83629. effect.setFloat("bloomWeight", _this.weight);
  83630. });
  83631. if (!blockCompilation) {
  83632. _this.updateEffect();
  83633. }
  83634. return _this;
  83635. }
  83636. return BloomMergePostProcess;
  83637. }(BABYLON.PostProcess));
  83638. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  83639. })(BABYLON || (BABYLON = {}));
  83640. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  83641. var BABYLON;
  83642. (function (BABYLON) {
  83643. /**
  83644. * 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.
  83645. */
  83646. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  83647. __extends(ExtractHighlightsPostProcess, _super);
  83648. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  83649. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  83650. if (blockCompilation === void 0) { blockCompilation = false; }
  83651. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  83652. /**
  83653. * The luminance threshold, pixels below this value will be set to black.
  83654. */
  83655. _this.threshold = 0.9;
  83656. /** @hidden */
  83657. _this._exposure = 1;
  83658. /**
  83659. * Post process which has the input texture to be used when performing highlight extraction
  83660. * @hidden
  83661. */
  83662. _this._inputPostProcess = null;
  83663. _this.onApplyObservable.add(function (effect) {
  83664. if (_this._inputPostProcess) {
  83665. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  83666. }
  83667. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  83668. effect.setFloat('exposure', _this._exposure);
  83669. });
  83670. return _this;
  83671. }
  83672. return ExtractHighlightsPostProcess;
  83673. }(BABYLON.PostProcess));
  83674. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  83675. })(BABYLON || (BABYLON = {}));
  83676. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  83677. var BABYLON;
  83678. (function (BABYLON) {
  83679. /**
  83680. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  83681. */
  83682. var BloomEffect = /** @class */ (function (_super) {
  83683. __extends(BloomEffect, _super);
  83684. /**
  83685. * Creates a new instance of @see BloomEffect
  83686. * @param scene The scene the effect belongs to.
  83687. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  83688. * @param bloomKernel The size of the kernel to be used when applying the blur.
  83689. * @param bloomWeight The the strength of bloom.
  83690. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  83691. * @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)
  83692. */
  83693. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  83694. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  83695. if (blockCompilation === void 0) { blockCompilation = false; }
  83696. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  83697. return _this._effects;
  83698. }, true) || this;
  83699. _this.bloomScale = bloomScale;
  83700. /**
  83701. * @hidden Internal
  83702. */
  83703. _this._effects = [];
  83704. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83705. _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);
  83706. _this._blurX.alwaysForcePOT = true;
  83707. _this._blurX.autoClear = false;
  83708. _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);
  83709. _this._blurY.alwaysForcePOT = true;
  83710. _this._blurY.autoClear = false;
  83711. _this.kernel = bloomKernel;
  83712. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  83713. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  83714. _this._merge.autoClear = false;
  83715. _this._effects.push(_this._merge);
  83716. return _this;
  83717. }
  83718. Object.defineProperty(BloomEffect.prototype, "threshold", {
  83719. /**
  83720. * The luminance threshold to find bright areas of the image to bloom.
  83721. */
  83722. get: function () {
  83723. return this._downscale.threshold;
  83724. },
  83725. set: function (value) {
  83726. this._downscale.threshold = value;
  83727. },
  83728. enumerable: true,
  83729. configurable: true
  83730. });
  83731. Object.defineProperty(BloomEffect.prototype, "weight", {
  83732. /**
  83733. * The strength of the bloom.
  83734. */
  83735. get: function () {
  83736. return this._merge.weight;
  83737. },
  83738. set: function (value) {
  83739. this._merge.weight = value;
  83740. },
  83741. enumerable: true,
  83742. configurable: true
  83743. });
  83744. Object.defineProperty(BloomEffect.prototype, "kernel", {
  83745. /**
  83746. * Specifies the size of the bloom blur kernel, relative to the final output size
  83747. */
  83748. get: function () {
  83749. return this._blurX.kernel / this.bloomScale;
  83750. },
  83751. set: function (value) {
  83752. this._blurX.kernel = value * this.bloomScale;
  83753. this._blurY.kernel = value * this.bloomScale;
  83754. },
  83755. enumerable: true,
  83756. configurable: true
  83757. });
  83758. /**
  83759. * Disposes each of the internal effects for a given camera.
  83760. * @param camera The camera to dispose the effect on.
  83761. */
  83762. BloomEffect.prototype.disposeEffects = function (camera) {
  83763. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83764. this._effects[effectIndex].dispose(camera);
  83765. }
  83766. };
  83767. /**
  83768. * @hidden Internal
  83769. */
  83770. BloomEffect.prototype._updateEffects = function () {
  83771. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83772. this._effects[effectIndex].updateEffect();
  83773. }
  83774. };
  83775. /**
  83776. * Internal
  83777. * @returns if all the contained post processes are ready.
  83778. * @hidden
  83779. */
  83780. BloomEffect.prototype._isReady = function () {
  83781. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  83782. if (!this._effects[effectIndex].isReady()) {
  83783. return false;
  83784. }
  83785. }
  83786. return true;
  83787. };
  83788. return BloomEffect;
  83789. }(BABYLON.PostProcessRenderEffect));
  83790. BABYLON.BloomEffect = BloomEffect;
  83791. })(BABYLON || (BABYLON = {}));
  83792. //# sourceMappingURL=babylon.bloomEffect.js.map
  83793. var BABYLON;
  83794. (function (BABYLON) {
  83795. /**
  83796. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  83797. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  83798. */
  83799. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  83800. __extends(DefaultRenderingPipeline, _super);
  83801. /**
  83802. * @constructor
  83803. * @param {string} name - The rendering pipeline name (default: "")
  83804. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  83805. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  83806. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  83807. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  83808. */
  83809. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  83810. if (name === void 0) { name = ""; }
  83811. if (hdr === void 0) { hdr = true; }
  83812. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  83813. if (automaticBuild === void 0) { automaticBuild = true; }
  83814. var _this = _super.call(this, scene.getEngine(), name) || this;
  83815. _this._camerasToBeAttached = [];
  83816. /**
  83817. * ID of the sharpen post process,
  83818. */
  83819. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  83820. /**
  83821. * ID of the image processing post process;
  83822. */
  83823. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  83824. /**
  83825. * ID of the Fast Approximate Anti-Aliasing post process;
  83826. */
  83827. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  83828. /**
  83829. * ID of the chromatic aberration post process,
  83830. */
  83831. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  83832. /**
  83833. * ID of the grain post process
  83834. */
  83835. _this.GrainPostProcessId = "GrainPostProcessEffect";
  83836. /**
  83837. * Glow post process which adds a glow to emmisive areas of the image
  83838. */
  83839. _this._glowLayer = null;
  83840. /**
  83841. * Animations which can be used to tweak settings over a period of time
  83842. */
  83843. _this.animations = [];
  83844. _this._imageProcessingConfigurationObserver = null;
  83845. // Values
  83846. _this._sharpenEnabled = false;
  83847. _this._bloomEnabled = false;
  83848. _this._depthOfFieldEnabled = false;
  83849. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  83850. _this._fxaaEnabled = false;
  83851. _this._imageProcessingEnabled = true;
  83852. _this._bloomScale = 0.5;
  83853. _this._chromaticAberrationEnabled = false;
  83854. _this._grainEnabled = false;
  83855. _this._buildAllowed = true;
  83856. _this._resizeObserver = null;
  83857. _this._hardwareScaleLevel = 1.0;
  83858. _this._bloomKernel = 64;
  83859. /**
  83860. * Specifies the weight of the bloom in the final rendering
  83861. */
  83862. _this._bloomWeight = 0.15;
  83863. /**
  83864. * Specifies the luma threshold for the area that will be blurred by the bloom
  83865. */
  83866. _this._bloomThreshold = 0.9;
  83867. _this._samples = 1;
  83868. _this._hasCleared = false;
  83869. _this._prevPostProcess = null;
  83870. _this._prevPrevPostProcess = null;
  83871. _this._depthOfFieldSceneObserver = null;
  83872. _this._cameras = cameras || scene.cameras;
  83873. _this._cameras = _this._cameras.slice();
  83874. _this._camerasToBeAttached = _this._cameras.slice();
  83875. _this._buildAllowed = automaticBuild;
  83876. // Initialize
  83877. _this._scene = scene;
  83878. var caps = _this._scene.getEngine().getCaps();
  83879. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  83880. // Misc
  83881. if (_this._hdr) {
  83882. if (caps.textureHalfFloatRender) {
  83883. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83884. }
  83885. else if (caps.textureFloatRender) {
  83886. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83887. }
  83888. }
  83889. else {
  83890. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83891. }
  83892. // Attach
  83893. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83894. var engine = _this._scene.getEngine();
  83895. // Create post processes before hand so they can be modified before enabled.
  83896. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  83897. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83898. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  83899. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  83900. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  83901. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83902. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  83903. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  83904. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  83905. _this._resizeObserver = engine.onResizeObservable.add(function () {
  83906. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  83907. _this.bloomKernel = _this.bloomKernel;
  83908. });
  83909. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  83910. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  83911. });
  83912. _this._buildPipeline();
  83913. return _this;
  83914. }
  83915. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  83916. get: function () {
  83917. return this._sharpenEnabled;
  83918. },
  83919. /**
  83920. * Enable or disable the sharpen process from the pipeline
  83921. */
  83922. set: function (enabled) {
  83923. if (this._sharpenEnabled === enabled) {
  83924. return;
  83925. }
  83926. this._sharpenEnabled = enabled;
  83927. this._buildPipeline();
  83928. },
  83929. enumerable: true,
  83930. configurable: true
  83931. });
  83932. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83933. /**
  83934. * Specifies the size of the bloom blur kernel, relative to the final output size
  83935. */
  83936. get: function () {
  83937. return this._bloomKernel;
  83938. },
  83939. set: function (value) {
  83940. this._bloomKernel = value;
  83941. this.bloom.kernel = value / this._hardwareScaleLevel;
  83942. },
  83943. enumerable: true,
  83944. configurable: true
  83945. });
  83946. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83947. get: function () {
  83948. return this._bloomWeight;
  83949. },
  83950. /**
  83951. * The strength of the bloom.
  83952. */
  83953. set: function (value) {
  83954. if (this._bloomWeight === value) {
  83955. return;
  83956. }
  83957. this.bloom.weight = value;
  83958. this._bloomWeight = value;
  83959. },
  83960. enumerable: true,
  83961. configurable: true
  83962. });
  83963. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83964. get: function () {
  83965. return this._bloomThreshold;
  83966. },
  83967. /**
  83968. * The strength of the bloom.
  83969. */
  83970. set: function (value) {
  83971. if (this._bloomThreshold === value) {
  83972. return;
  83973. }
  83974. this.bloom.threshold = value;
  83975. this._bloomThreshold = value;
  83976. },
  83977. enumerable: true,
  83978. configurable: true
  83979. });
  83980. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83981. get: function () {
  83982. return this._bloomScale;
  83983. },
  83984. /**
  83985. * The scale of the bloom, lower value will provide better performance.
  83986. */
  83987. set: function (value) {
  83988. if (this._bloomScale === value) {
  83989. return;
  83990. }
  83991. this._bloomScale = value;
  83992. // recreate bloom and dispose old as this setting is not dynamic
  83993. this._rebuildBloom();
  83994. this._buildPipeline();
  83995. },
  83996. enumerable: true,
  83997. configurable: true
  83998. });
  83999. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  84000. get: function () {
  84001. return this._bloomEnabled;
  84002. },
  84003. /**
  84004. * Enable or disable the bloom from the pipeline
  84005. */
  84006. set: function (enabled) {
  84007. if (this._bloomEnabled === enabled) {
  84008. return;
  84009. }
  84010. this._bloomEnabled = enabled;
  84011. this._buildPipeline();
  84012. },
  84013. enumerable: true,
  84014. configurable: true
  84015. });
  84016. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  84017. // recreate bloom and dispose old as this setting is not dynamic
  84018. var oldBloom = this.bloom;
  84019. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  84020. this.bloom.threshold = oldBloom.threshold;
  84021. for (var i = 0; i < this._cameras.length; i++) {
  84022. oldBloom.disposeEffects(this._cameras[i]);
  84023. }
  84024. };
  84025. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  84026. /**
  84027. * If the depth of field is enabled.
  84028. */
  84029. get: function () {
  84030. return this._depthOfFieldEnabled;
  84031. },
  84032. set: function (enabled) {
  84033. if (this._depthOfFieldEnabled === enabled) {
  84034. return;
  84035. }
  84036. this._depthOfFieldEnabled = enabled;
  84037. this._buildPipeline();
  84038. },
  84039. enumerable: true,
  84040. configurable: true
  84041. });
  84042. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  84043. /**
  84044. * Blur level of the depth of field effect. (Higher blur will effect performance)
  84045. */
  84046. get: function () {
  84047. return this._depthOfFieldBlurLevel;
  84048. },
  84049. set: function (value) {
  84050. if (this._depthOfFieldBlurLevel === value) {
  84051. return;
  84052. }
  84053. this._depthOfFieldBlurLevel = value;
  84054. // recreate dof and dispose old as this setting is not dynamic
  84055. var oldDof = this.depthOfField;
  84056. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  84057. this.depthOfField.focalLength = oldDof.focalLength;
  84058. this.depthOfField.focusDistance = oldDof.focusDistance;
  84059. this.depthOfField.fStop = oldDof.fStop;
  84060. this.depthOfField.lensSize = oldDof.lensSize;
  84061. for (var i = 0; i < this._cameras.length; i++) {
  84062. oldDof.disposeEffects(this._cameras[i]);
  84063. }
  84064. this._buildPipeline();
  84065. },
  84066. enumerable: true,
  84067. configurable: true
  84068. });
  84069. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  84070. get: function () {
  84071. return this._fxaaEnabled;
  84072. },
  84073. /**
  84074. * If the anti aliasing is enabled.
  84075. */
  84076. set: function (enabled) {
  84077. if (this._fxaaEnabled === enabled) {
  84078. return;
  84079. }
  84080. this._fxaaEnabled = enabled;
  84081. this._buildPipeline();
  84082. },
  84083. enumerable: true,
  84084. configurable: true
  84085. });
  84086. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  84087. get: function () {
  84088. return this._samples;
  84089. },
  84090. /**
  84091. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84092. */
  84093. set: function (sampleCount) {
  84094. if (this._samples === sampleCount) {
  84095. return;
  84096. }
  84097. this._samples = sampleCount;
  84098. this._buildPipeline();
  84099. },
  84100. enumerable: true,
  84101. configurable: true
  84102. });
  84103. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  84104. get: function () {
  84105. return this._imageProcessingEnabled;
  84106. },
  84107. /**
  84108. * If image processing is enabled.
  84109. */
  84110. set: function (enabled) {
  84111. if (this._imageProcessingEnabled === enabled) {
  84112. return;
  84113. }
  84114. this._imageProcessingEnabled = enabled;
  84115. this._buildPipeline();
  84116. },
  84117. enumerable: true,
  84118. configurable: true
  84119. });
  84120. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  84121. get: function () {
  84122. return this._glowLayer == null;
  84123. },
  84124. /**
  84125. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  84126. */
  84127. set: function (enabled) {
  84128. if (enabled && !this._glowLayer) {
  84129. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  84130. }
  84131. else if (!enabled && this._glowLayer) {
  84132. this._glowLayer.dispose();
  84133. this._glowLayer = null;
  84134. }
  84135. },
  84136. enumerable: true,
  84137. configurable: true
  84138. });
  84139. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  84140. get: function () {
  84141. return this._chromaticAberrationEnabled;
  84142. },
  84143. /**
  84144. * Enable or disable the chromaticAberration process from the pipeline
  84145. */
  84146. set: function (enabled) {
  84147. if (this._chromaticAberrationEnabled === enabled) {
  84148. return;
  84149. }
  84150. this._chromaticAberrationEnabled = enabled;
  84151. this._buildPipeline();
  84152. },
  84153. enumerable: true,
  84154. configurable: true
  84155. });
  84156. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  84157. get: function () {
  84158. return this._grainEnabled;
  84159. },
  84160. /**
  84161. * Enable or disable the grain process from the pipeline
  84162. */
  84163. set: function (enabled) {
  84164. if (this._grainEnabled === enabled) {
  84165. return;
  84166. }
  84167. this._grainEnabled = enabled;
  84168. this._buildPipeline();
  84169. },
  84170. enumerable: true,
  84171. configurable: true
  84172. });
  84173. /**
  84174. * Force the compilation of the entire pipeline.
  84175. */
  84176. DefaultRenderingPipeline.prototype.prepare = function () {
  84177. var previousState = this._buildAllowed;
  84178. this._buildAllowed = true;
  84179. this._buildPipeline();
  84180. this._buildAllowed = previousState;
  84181. };
  84182. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  84183. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  84184. if (this._hasCleared) {
  84185. postProcess.autoClear = false;
  84186. }
  84187. else {
  84188. postProcess.autoClear = true;
  84189. this._scene.autoClear = false;
  84190. this._hasCleared = true;
  84191. }
  84192. if (!skipTextureSharing) {
  84193. if (this._prevPrevPostProcess) {
  84194. postProcess.shareOutputWith(this._prevPrevPostProcess);
  84195. }
  84196. else {
  84197. postProcess.useOwnOutput();
  84198. }
  84199. if (this._prevPostProcess) {
  84200. this._prevPrevPostProcess = this._prevPostProcess;
  84201. }
  84202. this._prevPostProcess = postProcess;
  84203. }
  84204. };
  84205. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  84206. var _this = this;
  84207. if (!this._buildAllowed) {
  84208. return;
  84209. }
  84210. this._scene.autoClear = true;
  84211. var engine = this._scene.getEngine();
  84212. this._disposePostProcesses();
  84213. if (this._cameras !== null) {
  84214. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84215. // get back cameras to be used to reattach pipeline
  84216. this._cameras = this._camerasToBeAttached.slice();
  84217. }
  84218. this._reset();
  84219. this._prevPostProcess = null;
  84220. this._prevPrevPostProcess = null;
  84221. this._hasCleared = false;
  84222. if (this.depthOfFieldEnabled) {
  84223. // Multi camera suport
  84224. if (this._cameras.length > 1) {
  84225. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  84226. var camera = _a[_i];
  84227. var depthRenderer = this._scene.enableDepthRenderer(camera);
  84228. depthRenderer.useOnlyInActiveCamera = true;
  84229. }
  84230. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  84231. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  84232. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  84233. }
  84234. });
  84235. }
  84236. else {
  84237. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84238. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  84239. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  84240. }
  84241. if (!this.depthOfField._isReady()) {
  84242. this.depthOfField._updateEffects();
  84243. }
  84244. this.addEffect(this.depthOfField);
  84245. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  84246. }
  84247. else {
  84248. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84249. }
  84250. if (this.bloomEnabled) {
  84251. if (!this.bloom._isReady()) {
  84252. this.bloom._updateEffects();
  84253. }
  84254. this.addEffect(this.bloom);
  84255. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  84256. }
  84257. if (this._imageProcessingEnabled) {
  84258. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84259. if (this._hdr) {
  84260. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  84261. this._setAutoClearAndTextureSharing(this.imageProcessing);
  84262. }
  84263. else {
  84264. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  84265. }
  84266. }
  84267. if (this.sharpenEnabled) {
  84268. if (!this.sharpen.isReady()) {
  84269. this.sharpen.updateEffect();
  84270. }
  84271. this.addEffect(this._sharpenEffect);
  84272. this._setAutoClearAndTextureSharing(this.sharpen);
  84273. }
  84274. if (this.grainEnabled) {
  84275. if (!this.grain.isReady()) {
  84276. this.grain.updateEffect();
  84277. }
  84278. this.addEffect(this._grainEffect);
  84279. this._setAutoClearAndTextureSharing(this.grain);
  84280. }
  84281. if (this.chromaticAberrationEnabled) {
  84282. if (!this.chromaticAberration.isReady()) {
  84283. this.chromaticAberration.updateEffect();
  84284. }
  84285. this.addEffect(this._chromaticAberrationEffect);
  84286. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  84287. }
  84288. if (this.fxaaEnabled) {
  84289. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  84290. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  84291. this._setAutoClearAndTextureSharing(this.fxaa, true);
  84292. }
  84293. if (this._cameras !== null) {
  84294. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84295. }
  84296. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  84297. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84298. }
  84299. };
  84300. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  84301. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  84302. for (var i = 0; i < this._cameras.length; i++) {
  84303. var camera = this._cameras[i];
  84304. if (this.imageProcessing) {
  84305. this.imageProcessing.dispose(camera);
  84306. }
  84307. if (this.fxaa) {
  84308. this.fxaa.dispose(camera);
  84309. }
  84310. // These are created in the constructor and should not be disposed on every pipeline change
  84311. if (disposeNonRecreated) {
  84312. if (this.sharpen) {
  84313. this.sharpen.dispose(camera);
  84314. }
  84315. if (this.depthOfField) {
  84316. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  84317. this.depthOfField.disposeEffects(camera);
  84318. }
  84319. if (this.bloom) {
  84320. this.bloom.disposeEffects(camera);
  84321. }
  84322. if (this.chromaticAberration) {
  84323. this.chromaticAberration.dispose(camera);
  84324. }
  84325. if (this.grain) {
  84326. this.grain.dispose(camera);
  84327. }
  84328. if (this._glowLayer) {
  84329. this._glowLayer.dispose();
  84330. }
  84331. }
  84332. }
  84333. this.imageProcessing = null;
  84334. this.fxaa = null;
  84335. if (disposeNonRecreated) {
  84336. this.sharpen = null;
  84337. this._sharpenEffect = null;
  84338. this.depthOfField = null;
  84339. this.bloom = null;
  84340. this.chromaticAberration = null;
  84341. this._chromaticAberrationEffect = null;
  84342. this.grain = null;
  84343. this._grainEffect = null;
  84344. this._glowLayer = null;
  84345. }
  84346. };
  84347. /**
  84348. * Adds a camera to the pipeline
  84349. * @param camera the camera to be added
  84350. */
  84351. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  84352. this._camerasToBeAttached.push(camera);
  84353. this._buildPipeline();
  84354. };
  84355. /**
  84356. * Removes a camera from the pipeline
  84357. * @param camera the camera to remove
  84358. */
  84359. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  84360. var index = this._camerasToBeAttached.indexOf(camera);
  84361. this._camerasToBeAttached.splice(index, 1);
  84362. this._buildPipeline();
  84363. };
  84364. /**
  84365. * Dispose of the pipeline and stop all post processes
  84366. */
  84367. DefaultRenderingPipeline.prototype.dispose = function () {
  84368. this._disposePostProcesses(true);
  84369. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84370. this._scene.autoClear = true;
  84371. if (this._resizeObserver) {
  84372. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  84373. this._resizeObserver = null;
  84374. }
  84375. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  84376. _super.prototype.dispose.call(this);
  84377. };
  84378. /**
  84379. * Serialize the rendering pipeline (Used when exporting)
  84380. * @returns the serialized object
  84381. */
  84382. DefaultRenderingPipeline.prototype.serialize = function () {
  84383. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84384. serializationObject.customType = "DefaultRenderingPipeline";
  84385. return serializationObject;
  84386. };
  84387. /**
  84388. * Parse the serialized pipeline
  84389. * @param source Source pipeline.
  84390. * @param scene The scene to load the pipeline to.
  84391. * @param rootUrl The URL of the serialized pipeline.
  84392. * @returns An instantiated pipeline from the serialized object.
  84393. */
  84394. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84395. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  84396. };
  84397. __decorate([
  84398. BABYLON.serialize()
  84399. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  84400. __decorate([
  84401. BABYLON.serialize()
  84402. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  84403. __decorate([
  84404. BABYLON.serialize()
  84405. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  84406. __decorate([
  84407. BABYLON.serialize()
  84408. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  84409. __decorate([
  84410. BABYLON.serialize()
  84411. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  84412. __decorate([
  84413. BABYLON.serialize()
  84414. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  84415. __decorate([
  84416. BABYLON.serialize()
  84417. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  84418. __decorate([
  84419. BABYLON.serialize()
  84420. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  84421. __decorate([
  84422. BABYLON.serialize()
  84423. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  84424. __decorate([
  84425. BABYLON.serialize()
  84426. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  84427. __decorate([
  84428. BABYLON.serialize()
  84429. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  84430. __decorate([
  84431. BABYLON.serialize()
  84432. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  84433. __decorate([
  84434. BABYLON.serialize()
  84435. ], DefaultRenderingPipeline.prototype, "samples", null);
  84436. __decorate([
  84437. BABYLON.serialize()
  84438. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  84439. __decorate([
  84440. BABYLON.serialize()
  84441. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  84442. __decorate([
  84443. BABYLON.serialize()
  84444. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  84445. __decorate([
  84446. BABYLON.serialize()
  84447. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  84448. return DefaultRenderingPipeline;
  84449. }(BABYLON.PostProcessRenderPipeline));
  84450. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  84451. })(BABYLON || (BABYLON = {}));
  84452. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  84453. var BABYLON;
  84454. (function (BABYLON) {
  84455. /**
  84456. * @hidden
  84457. */
  84458. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  84459. __extends(ImageProcessingConfigurationDefines, _super);
  84460. function ImageProcessingConfigurationDefines() {
  84461. var _this = _super.call(this) || this;
  84462. _this.IMAGEPROCESSING = false;
  84463. _this.VIGNETTE = false;
  84464. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  84465. _this.VIGNETTEBLENDMODEOPAQUE = false;
  84466. _this.TONEMAPPING = false;
  84467. _this.TONEMAPPING_ACES = false;
  84468. _this.CONTRAST = false;
  84469. _this.COLORCURVES = false;
  84470. _this.COLORGRADING = false;
  84471. _this.COLORGRADING3D = false;
  84472. _this.SAMPLER3DGREENDEPTH = false;
  84473. _this.SAMPLER3DBGRMAP = false;
  84474. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  84475. _this.EXPOSURE = false;
  84476. _this.rebuild();
  84477. return _this;
  84478. }
  84479. return ImageProcessingConfigurationDefines;
  84480. }(BABYLON.MaterialDefines));
  84481. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  84482. /**
  84483. * This groups together the common properties used for image processing either in direct forward pass
  84484. * or through post processing effect depending on the use of the image processing pipeline in your scene
  84485. * or not.
  84486. */
  84487. var ImageProcessingConfiguration = /** @class */ (function () {
  84488. function ImageProcessingConfiguration() {
  84489. /**
  84490. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  84491. */
  84492. this.colorCurves = new BABYLON.ColorCurves();
  84493. this._colorCurvesEnabled = false;
  84494. this._colorGradingEnabled = false;
  84495. this._colorGradingWithGreenDepth = true;
  84496. this._colorGradingBGR = true;
  84497. /** @hidden */
  84498. this._exposure = 1.0;
  84499. this._toneMappingEnabled = false;
  84500. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  84501. this._contrast = 1.0;
  84502. /**
  84503. * Vignette stretch size.
  84504. */
  84505. this.vignetteStretch = 0;
  84506. /**
  84507. * Vignette centre X Offset.
  84508. */
  84509. this.vignetteCentreX = 0;
  84510. /**
  84511. * Vignette centre Y Offset.
  84512. */
  84513. this.vignetteCentreY = 0;
  84514. /**
  84515. * Vignette weight or intensity of the vignette effect.
  84516. */
  84517. this.vignetteWeight = 1.5;
  84518. /**
  84519. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  84520. * if vignetteEnabled is set to true.
  84521. */
  84522. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  84523. /**
  84524. * Camera field of view used by the Vignette effect.
  84525. */
  84526. this.vignetteCameraFov = 0.5;
  84527. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  84528. this._vignetteEnabled = false;
  84529. this._applyByPostProcess = false;
  84530. this._isEnabled = true;
  84531. /**
  84532. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  84533. */
  84534. this.onUpdateParameters = new BABYLON.Observable();
  84535. }
  84536. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  84537. /**
  84538. * Gets wether the color curves effect is enabled.
  84539. */
  84540. get: function () {
  84541. return this._colorCurvesEnabled;
  84542. },
  84543. /**
  84544. * Sets wether the color curves effect is enabled.
  84545. */
  84546. set: function (value) {
  84547. if (this._colorCurvesEnabled === value) {
  84548. return;
  84549. }
  84550. this._colorCurvesEnabled = value;
  84551. this._updateParameters();
  84552. },
  84553. enumerable: true,
  84554. configurable: true
  84555. });
  84556. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  84557. /**
  84558. * Gets wether the color grading effect is enabled.
  84559. */
  84560. get: function () {
  84561. return this._colorGradingEnabled;
  84562. },
  84563. /**
  84564. * Sets wether the color grading effect is enabled.
  84565. */
  84566. set: function (value) {
  84567. if (this._colorGradingEnabled === value) {
  84568. return;
  84569. }
  84570. this._colorGradingEnabled = value;
  84571. this._updateParameters();
  84572. },
  84573. enumerable: true,
  84574. configurable: true
  84575. });
  84576. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  84577. /**
  84578. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  84579. */
  84580. get: function () {
  84581. return this._colorGradingWithGreenDepth;
  84582. },
  84583. /**
  84584. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  84585. */
  84586. set: function (value) {
  84587. if (this._colorGradingWithGreenDepth === value) {
  84588. return;
  84589. }
  84590. this._colorGradingWithGreenDepth = value;
  84591. this._updateParameters();
  84592. },
  84593. enumerable: true,
  84594. configurable: true
  84595. });
  84596. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  84597. /**
  84598. * Gets wether the color grading texture contains BGR values.
  84599. */
  84600. get: function () {
  84601. return this._colorGradingBGR;
  84602. },
  84603. /**
  84604. * Sets wether the color grading texture contains BGR values.
  84605. */
  84606. set: function (value) {
  84607. if (this._colorGradingBGR === value) {
  84608. return;
  84609. }
  84610. this._colorGradingBGR = value;
  84611. this._updateParameters();
  84612. },
  84613. enumerable: true,
  84614. configurable: true
  84615. });
  84616. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  84617. /**
  84618. * Gets the Exposure used in the effect.
  84619. */
  84620. get: function () {
  84621. return this._exposure;
  84622. },
  84623. /**
  84624. * Sets the Exposure used in the effect.
  84625. */
  84626. set: function (value) {
  84627. if (this._exposure === value) {
  84628. return;
  84629. }
  84630. this._exposure = value;
  84631. this._updateParameters();
  84632. },
  84633. enumerable: true,
  84634. configurable: true
  84635. });
  84636. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  84637. /**
  84638. * Gets wether the tone mapping effect is enabled.
  84639. */
  84640. get: function () {
  84641. return this._toneMappingEnabled;
  84642. },
  84643. /**
  84644. * Sets wether the tone mapping effect is enabled.
  84645. */
  84646. set: function (value) {
  84647. if (this._toneMappingEnabled === value) {
  84648. return;
  84649. }
  84650. this._toneMappingEnabled = value;
  84651. this._updateParameters();
  84652. },
  84653. enumerable: true,
  84654. configurable: true
  84655. });
  84656. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  84657. /**
  84658. * Gets the type of tone mapping effect.
  84659. */
  84660. get: function () {
  84661. return this._toneMappingType;
  84662. },
  84663. /**
  84664. * Sets the type of tone mapping effect used in BabylonJS.
  84665. */
  84666. set: function (value) {
  84667. if (this._toneMappingType === value) {
  84668. return;
  84669. }
  84670. this._toneMappingType = value;
  84671. this._updateParameters();
  84672. },
  84673. enumerable: true,
  84674. configurable: true
  84675. });
  84676. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  84677. /**
  84678. * Gets the contrast used in the effect.
  84679. */
  84680. get: function () {
  84681. return this._contrast;
  84682. },
  84683. /**
  84684. * Sets the contrast used in the effect.
  84685. */
  84686. set: function (value) {
  84687. if (this._contrast === value) {
  84688. return;
  84689. }
  84690. this._contrast = value;
  84691. this._updateParameters();
  84692. },
  84693. enumerable: true,
  84694. configurable: true
  84695. });
  84696. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  84697. /**
  84698. * Gets the vignette blend mode allowing different kind of effect.
  84699. */
  84700. get: function () {
  84701. return this._vignetteBlendMode;
  84702. },
  84703. /**
  84704. * Sets the vignette blend mode allowing different kind of effect.
  84705. */
  84706. set: function (value) {
  84707. if (this._vignetteBlendMode === value) {
  84708. return;
  84709. }
  84710. this._vignetteBlendMode = value;
  84711. this._updateParameters();
  84712. },
  84713. enumerable: true,
  84714. configurable: true
  84715. });
  84716. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  84717. /**
  84718. * Gets wether the vignette effect is enabled.
  84719. */
  84720. get: function () {
  84721. return this._vignetteEnabled;
  84722. },
  84723. /**
  84724. * Sets wether the vignette effect is enabled.
  84725. */
  84726. set: function (value) {
  84727. if (this._vignetteEnabled === value) {
  84728. return;
  84729. }
  84730. this._vignetteEnabled = value;
  84731. this._updateParameters();
  84732. },
  84733. enumerable: true,
  84734. configurable: true
  84735. });
  84736. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  84737. /**
  84738. * Gets wether the image processing is applied through a post process or not.
  84739. */
  84740. get: function () {
  84741. return this._applyByPostProcess;
  84742. },
  84743. /**
  84744. * Sets wether the image processing is applied through a post process or not.
  84745. */
  84746. set: function (value) {
  84747. if (this._applyByPostProcess === value) {
  84748. return;
  84749. }
  84750. this._applyByPostProcess = value;
  84751. this._updateParameters();
  84752. },
  84753. enumerable: true,
  84754. configurable: true
  84755. });
  84756. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  84757. /**
  84758. * Gets wether the image processing is enabled or not.
  84759. */
  84760. get: function () {
  84761. return this._isEnabled;
  84762. },
  84763. /**
  84764. * Sets wether the image processing is enabled or not.
  84765. */
  84766. set: function (value) {
  84767. if (this._isEnabled === value) {
  84768. return;
  84769. }
  84770. this._isEnabled = value;
  84771. this._updateParameters();
  84772. },
  84773. enumerable: true,
  84774. configurable: true
  84775. });
  84776. /**
  84777. * Method called each time the image processing information changes requires to recompile the effect.
  84778. */
  84779. ImageProcessingConfiguration.prototype._updateParameters = function () {
  84780. this.onUpdateParameters.notifyObservers(this);
  84781. };
  84782. ImageProcessingConfiguration.prototype.getClassName = function () {
  84783. return "ImageProcessingConfiguration";
  84784. };
  84785. /**
  84786. * Prepare the list of uniforms associated with the Image Processing effects.
  84787. * @param uniformsList The list of uniforms used in the effect
  84788. * @param defines the list of defines currently in use
  84789. */
  84790. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  84791. if (defines.EXPOSURE) {
  84792. uniforms.push("exposureLinear");
  84793. }
  84794. if (defines.CONTRAST) {
  84795. uniforms.push("contrast");
  84796. }
  84797. if (defines.COLORGRADING) {
  84798. uniforms.push("colorTransformSettings");
  84799. }
  84800. if (defines.VIGNETTE) {
  84801. uniforms.push("vInverseScreenSize");
  84802. uniforms.push("vignetteSettings1");
  84803. uniforms.push("vignetteSettings2");
  84804. }
  84805. if (defines.COLORCURVES) {
  84806. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  84807. }
  84808. };
  84809. /**
  84810. * Prepare the list of samplers associated with the Image Processing effects.
  84811. * @param uniformsList The list of uniforms used in the effect
  84812. * @param defines the list of defines currently in use
  84813. */
  84814. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  84815. if (defines.COLORGRADING) {
  84816. samplersList.push("txColorTransform");
  84817. }
  84818. };
  84819. /**
  84820. * Prepare the list of defines associated to the shader.
  84821. * @param defines the list of defines to complete
  84822. */
  84823. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  84824. if (forPostProcess === void 0) { forPostProcess = false; }
  84825. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  84826. defines.VIGNETTE = false;
  84827. defines.TONEMAPPING = false;
  84828. defines.TONEMAPPING_ACES = false;
  84829. defines.CONTRAST = false;
  84830. defines.EXPOSURE = false;
  84831. defines.COLORCURVES = false;
  84832. defines.COLORGRADING = false;
  84833. defines.COLORGRADING3D = false;
  84834. defines.IMAGEPROCESSING = false;
  84835. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  84836. return;
  84837. }
  84838. defines.VIGNETTE = this.vignetteEnabled;
  84839. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  84840. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  84841. defines.TONEMAPPING = this.toneMappingEnabled;
  84842. switch (this._toneMappingType) {
  84843. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  84844. defines.TONEMAPPING_ACES = true;
  84845. break;
  84846. }
  84847. defines.CONTRAST = (this.contrast !== 1.0);
  84848. defines.EXPOSURE = (this.exposure !== 1.0);
  84849. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  84850. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  84851. if (defines.COLORGRADING) {
  84852. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  84853. }
  84854. else {
  84855. defines.COLORGRADING3D = false;
  84856. }
  84857. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  84858. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  84859. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  84860. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  84861. };
  84862. /**
  84863. * Returns true if all the image processing information are ready.
  84864. */
  84865. ImageProcessingConfiguration.prototype.isReady = function () {
  84866. // Color Grading texure can not be none blocking.
  84867. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  84868. };
  84869. /**
  84870. * Binds the image processing to the shader.
  84871. * @param effect The effect to bind to
  84872. */
  84873. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  84874. if (aspectRatio === void 0) { aspectRatio = 1; }
  84875. // Color Curves
  84876. if (this._colorCurvesEnabled && this.colorCurves) {
  84877. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  84878. }
  84879. // Vignette
  84880. if (this._vignetteEnabled) {
  84881. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  84882. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  84883. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  84884. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  84885. var vignetteScaleX = vignetteScaleY * aspectRatio;
  84886. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  84887. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  84888. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  84889. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  84890. var vignettePower = -2.0 * this.vignetteWeight;
  84891. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  84892. }
  84893. // Exposure
  84894. effect.setFloat("exposureLinear", this.exposure);
  84895. // Contrast
  84896. effect.setFloat("contrast", this.contrast);
  84897. // Color transform settings
  84898. if (this.colorGradingTexture) {
  84899. effect.setTexture("txColorTransform", this.colorGradingTexture);
  84900. var textureSize = this.colorGradingTexture.getSize().height;
  84901. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  84902. 0.5 / textureSize, // textureOffset
  84903. textureSize, // textureSize
  84904. this.colorGradingTexture.level // weight
  84905. );
  84906. }
  84907. };
  84908. /**
  84909. * Clones the current image processing instance.
  84910. * @return The cloned image processing
  84911. */
  84912. ImageProcessingConfiguration.prototype.clone = function () {
  84913. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  84914. };
  84915. /**
  84916. * Serializes the current image processing instance to a json representation.
  84917. * @return a JSON representation
  84918. */
  84919. ImageProcessingConfiguration.prototype.serialize = function () {
  84920. return BABYLON.SerializationHelper.Serialize(this);
  84921. };
  84922. /**
  84923. * Parses the image processing from a json representation.
  84924. * @param source the JSON source to parse
  84925. * @return The parsed image processing
  84926. */
  84927. ImageProcessingConfiguration.Parse = function (source) {
  84928. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  84929. };
  84930. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  84931. /**
  84932. * Used to apply the vignette as a mix with the pixel color.
  84933. */
  84934. get: function () {
  84935. return this._VIGNETTEMODE_MULTIPLY;
  84936. },
  84937. enumerable: true,
  84938. configurable: true
  84939. });
  84940. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84941. /**
  84942. * Used to apply the vignette as a replacement of the pixel color.
  84943. */
  84944. get: function () {
  84945. return this._VIGNETTEMODE_OPAQUE;
  84946. },
  84947. enumerable: true,
  84948. configurable: true
  84949. });
  84950. /**
  84951. * Default tone mapping applied in BabylonJS.
  84952. */
  84953. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84954. /**
  84955. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84956. * to other engines rendering to increase portability.
  84957. */
  84958. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84959. // Static constants associated to the image processing.
  84960. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84961. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84962. __decorate([
  84963. BABYLON.serializeAsColorCurves()
  84964. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84965. __decorate([
  84966. BABYLON.serialize()
  84967. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84968. __decorate([
  84969. BABYLON.serializeAsTexture()
  84970. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84971. __decorate([
  84972. BABYLON.serialize()
  84973. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84974. __decorate([
  84975. BABYLON.serialize()
  84976. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84977. __decorate([
  84978. BABYLON.serialize()
  84979. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84980. __decorate([
  84981. BABYLON.serialize()
  84982. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84983. __decorate([
  84984. BABYLON.serialize()
  84985. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84986. __decorate([
  84987. BABYLON.serialize()
  84988. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84989. __decorate([
  84990. BABYLON.serialize()
  84991. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84992. __decorate([
  84993. BABYLON.serialize()
  84994. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84995. __decorate([
  84996. BABYLON.serialize()
  84997. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84998. __decorate([
  84999. BABYLON.serialize()
  85000. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  85001. __decorate([
  85002. BABYLON.serialize()
  85003. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  85004. __decorate([
  85005. BABYLON.serializeAsColor4()
  85006. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  85007. __decorate([
  85008. BABYLON.serialize()
  85009. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  85010. __decorate([
  85011. BABYLON.serialize()
  85012. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  85013. __decorate([
  85014. BABYLON.serialize()
  85015. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  85016. __decorate([
  85017. BABYLON.serialize()
  85018. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  85019. __decorate([
  85020. BABYLON.serialize()
  85021. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  85022. return ImageProcessingConfiguration;
  85023. }());
  85024. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  85025. })(BABYLON || (BABYLON = {}));
  85026. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  85027. var BABYLON;
  85028. (function (BABYLON) {
  85029. /**
  85030. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  85031. * It can help converting any input color in a desired output one. This can then be used to create effects
  85032. * from sepia, black and white to sixties or futuristic rendering...
  85033. *
  85034. * The only supported format is currently 3dl.
  85035. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  85036. */
  85037. var ColorGradingTexture = /** @class */ (function (_super) {
  85038. __extends(ColorGradingTexture, _super);
  85039. /**
  85040. * Instantiates a ColorGradingTexture from the following parameters.
  85041. *
  85042. * @param url The location of the color gradind data (currently only supporting 3dl)
  85043. * @param scene The scene the texture will be used in
  85044. */
  85045. function ColorGradingTexture(url, scene) {
  85046. var _this = _super.call(this, scene) || this;
  85047. if (!url) {
  85048. return _this;
  85049. }
  85050. _this._engine = scene.getEngine();
  85051. _this._textureMatrix = BABYLON.Matrix.Identity();
  85052. _this.name = url;
  85053. _this.url = url;
  85054. _this.hasAlpha = false;
  85055. _this.isCube = false;
  85056. _this.is3D = _this._engine.webGLVersion > 1;
  85057. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85058. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85059. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85060. _this.anisotropicFilteringLevel = 1;
  85061. _this._texture = _this._getFromCache(url, true);
  85062. if (!_this._texture) {
  85063. if (!scene.useDelayedTextureLoading) {
  85064. _this.loadTexture();
  85065. }
  85066. else {
  85067. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  85068. }
  85069. }
  85070. return _this;
  85071. }
  85072. /**
  85073. * Returns the texture matrix used in most of the material.
  85074. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  85075. */
  85076. ColorGradingTexture.prototype.getTextureMatrix = function () {
  85077. return this._textureMatrix;
  85078. };
  85079. /**
  85080. * Occurs when the file being loaded is a .3dl LUT file.
  85081. */
  85082. ColorGradingTexture.prototype.load3dlTexture = function () {
  85083. var engine = this._engine;
  85084. var texture;
  85085. if (engine.webGLVersion === 1) {
  85086. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85087. }
  85088. else {
  85089. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85090. }
  85091. this._texture = texture;
  85092. var callback = function (text) {
  85093. if (typeof text !== "string") {
  85094. return;
  85095. }
  85096. var data = null;
  85097. var tempData = null;
  85098. var line;
  85099. var lines = text.split('\n');
  85100. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  85101. var maxColor = 0;
  85102. for (var i = 0; i < lines.length; i++) {
  85103. line = lines[i];
  85104. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  85105. continue;
  85106. if (line.indexOf('#') === 0)
  85107. continue;
  85108. var words = line.split(" ");
  85109. if (size === 0) {
  85110. // Number of space + one
  85111. size = words.length;
  85112. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  85113. tempData = new Float32Array(size * size * size * 4);
  85114. continue;
  85115. }
  85116. if (size != 0) {
  85117. var r = Math.max(parseInt(words[0]), 0);
  85118. var g = Math.max(parseInt(words[1]), 0);
  85119. var b = Math.max(parseInt(words[2]), 0);
  85120. maxColor = Math.max(r, maxColor);
  85121. maxColor = Math.max(g, maxColor);
  85122. maxColor = Math.max(b, maxColor);
  85123. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  85124. if (tempData) {
  85125. tempData[pixelStorageIndex + 0] = r;
  85126. tempData[pixelStorageIndex + 1] = g;
  85127. tempData[pixelStorageIndex + 2] = b;
  85128. }
  85129. pixelIndexSlice++;
  85130. if (pixelIndexSlice % size == 0) {
  85131. pixelIndexH++;
  85132. pixelIndexSlice = 0;
  85133. if (pixelIndexH % size == 0) {
  85134. pixelIndexW++;
  85135. pixelIndexH = 0;
  85136. }
  85137. }
  85138. }
  85139. }
  85140. if (tempData && data) {
  85141. for (var i = 0; i < tempData.length; i++) {
  85142. if (i > 0 && (i + 1) % 4 === 0) {
  85143. data[i] = 255;
  85144. }
  85145. else {
  85146. var value = tempData[i];
  85147. data[i] = (value / maxColor * 255);
  85148. }
  85149. }
  85150. }
  85151. if (texture.is3D) {
  85152. texture.updateSize(size, size, size);
  85153. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85154. }
  85155. else {
  85156. texture.updateSize(size * size, size);
  85157. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  85158. }
  85159. };
  85160. var scene = this.getScene();
  85161. if (scene) {
  85162. scene._loadFile(this.url, callback);
  85163. }
  85164. else {
  85165. this._engine._loadFile(this.url, callback);
  85166. }
  85167. return this._texture;
  85168. };
  85169. /**
  85170. * Starts the loading process of the texture.
  85171. */
  85172. ColorGradingTexture.prototype.loadTexture = function () {
  85173. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  85174. this.load3dlTexture();
  85175. }
  85176. };
  85177. /**
  85178. * Clones the color gradind texture.
  85179. */
  85180. ColorGradingTexture.prototype.clone = function () {
  85181. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  85182. // Base texture
  85183. newTexture.level = this.level;
  85184. return newTexture;
  85185. };
  85186. /**
  85187. * Called during delayed load for textures.
  85188. */
  85189. ColorGradingTexture.prototype.delayLoad = function () {
  85190. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  85191. return;
  85192. }
  85193. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  85194. this._texture = this._getFromCache(this.url, true);
  85195. if (!this._texture) {
  85196. this.loadTexture();
  85197. }
  85198. };
  85199. /**
  85200. * Parses a color grading texture serialized by Babylon.
  85201. * @param parsedTexture The texture information being parsedTexture
  85202. * @param scene The scene to load the texture in
  85203. * @param rootUrl The root url of the data assets to load
  85204. * @return A color gradind texture
  85205. */
  85206. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  85207. var texture = null;
  85208. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  85209. texture = new ColorGradingTexture(parsedTexture.name, scene);
  85210. texture.name = parsedTexture.name;
  85211. texture.level = parsedTexture.level;
  85212. }
  85213. return texture;
  85214. };
  85215. /**
  85216. * Serializes the LUT texture to json format.
  85217. */
  85218. ColorGradingTexture.prototype.serialize = function () {
  85219. if (!this.name) {
  85220. return null;
  85221. }
  85222. var serializationObject = {};
  85223. serializationObject.name = this.name;
  85224. serializationObject.level = this.level;
  85225. serializationObject.customType = "BABYLON.ColorGradingTexture";
  85226. return serializationObject;
  85227. };
  85228. /**
  85229. * Empty line regex stored for GC.
  85230. */
  85231. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  85232. return ColorGradingTexture;
  85233. }(BABYLON.BaseTexture));
  85234. BABYLON.ColorGradingTexture = ColorGradingTexture;
  85235. })(BABYLON || (BABYLON = {}));
  85236. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  85237. var BABYLON;
  85238. (function (BABYLON) {
  85239. /**
  85240. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  85241. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  85242. * 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;
  85243. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  85244. */
  85245. var ColorCurves = /** @class */ (function () {
  85246. function ColorCurves() {
  85247. this._dirty = true;
  85248. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  85249. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  85250. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85251. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  85252. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  85253. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  85254. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  85255. this._globalHue = 30;
  85256. this._globalDensity = 0;
  85257. this._globalSaturation = 0;
  85258. this._globalExposure = 0;
  85259. this._highlightsHue = 30;
  85260. this._highlightsDensity = 0;
  85261. this._highlightsSaturation = 0;
  85262. this._highlightsExposure = 0;
  85263. this._midtonesHue = 30;
  85264. this._midtonesDensity = 0;
  85265. this._midtonesSaturation = 0;
  85266. this._midtonesExposure = 0;
  85267. this._shadowsHue = 30;
  85268. this._shadowsDensity = 0;
  85269. this._shadowsSaturation = 0;
  85270. this._shadowsExposure = 0;
  85271. }
  85272. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  85273. /**
  85274. * Gets the global Hue value.
  85275. * 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).
  85276. */
  85277. get: function () {
  85278. return this._globalHue;
  85279. },
  85280. /**
  85281. * Sets the global Hue value.
  85282. * 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).
  85283. */
  85284. set: function (value) {
  85285. this._globalHue = value;
  85286. this._dirty = true;
  85287. },
  85288. enumerable: true,
  85289. configurable: true
  85290. });
  85291. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  85292. /**
  85293. * Gets the global Density value.
  85294. * 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.
  85295. * Values less than zero provide a filter of opposite hue.
  85296. */
  85297. get: function () {
  85298. return this._globalDensity;
  85299. },
  85300. /**
  85301. * Sets the global Density value.
  85302. * 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.
  85303. * Values less than zero provide a filter of opposite hue.
  85304. */
  85305. set: function (value) {
  85306. this._globalDensity = value;
  85307. this._dirty = true;
  85308. },
  85309. enumerable: true,
  85310. configurable: true
  85311. });
  85312. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  85313. /**
  85314. * Gets the global Saturation value.
  85315. * 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.
  85316. */
  85317. get: function () {
  85318. return this._globalSaturation;
  85319. },
  85320. /**
  85321. * Sets the global Saturation value.
  85322. * 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.
  85323. */
  85324. set: function (value) {
  85325. this._globalSaturation = value;
  85326. this._dirty = true;
  85327. },
  85328. enumerable: true,
  85329. configurable: true
  85330. });
  85331. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  85332. /**
  85333. * Gets the global Exposure value.
  85334. * 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.
  85335. */
  85336. get: function () {
  85337. return this._globalExposure;
  85338. },
  85339. /**
  85340. * Sets the global Exposure value.
  85341. * 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.
  85342. */
  85343. set: function (value) {
  85344. this._globalExposure = value;
  85345. this._dirty = true;
  85346. },
  85347. enumerable: true,
  85348. configurable: true
  85349. });
  85350. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  85351. /**
  85352. * Gets the highlights Hue value.
  85353. * 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).
  85354. */
  85355. get: function () {
  85356. return this._highlightsHue;
  85357. },
  85358. /**
  85359. * Sets the highlights Hue value.
  85360. * 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).
  85361. */
  85362. set: function (value) {
  85363. this._highlightsHue = value;
  85364. this._dirty = true;
  85365. },
  85366. enumerable: true,
  85367. configurable: true
  85368. });
  85369. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  85370. /**
  85371. * Gets the highlights Density value.
  85372. * 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.
  85373. * Values less than zero provide a filter of opposite hue.
  85374. */
  85375. get: function () {
  85376. return this._highlightsDensity;
  85377. },
  85378. /**
  85379. * Sets the highlights Density value.
  85380. * 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.
  85381. * Values less than zero provide a filter of opposite hue.
  85382. */
  85383. set: function (value) {
  85384. this._highlightsDensity = value;
  85385. this._dirty = true;
  85386. },
  85387. enumerable: true,
  85388. configurable: true
  85389. });
  85390. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  85391. /**
  85392. * Gets the highlights Saturation value.
  85393. * 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.
  85394. */
  85395. get: function () {
  85396. return this._highlightsSaturation;
  85397. },
  85398. /**
  85399. * Sets the highlights Saturation value.
  85400. * 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.
  85401. */
  85402. set: function (value) {
  85403. this._highlightsSaturation = value;
  85404. this._dirty = true;
  85405. },
  85406. enumerable: true,
  85407. configurable: true
  85408. });
  85409. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  85410. /**
  85411. * Gets the highlights Exposure value.
  85412. * 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.
  85413. */
  85414. get: function () {
  85415. return this._highlightsExposure;
  85416. },
  85417. /**
  85418. * Sets the highlights Exposure value.
  85419. * 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.
  85420. */
  85421. set: function (value) {
  85422. this._highlightsExposure = value;
  85423. this._dirty = true;
  85424. },
  85425. enumerable: true,
  85426. configurable: true
  85427. });
  85428. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  85429. /**
  85430. * Gets the midtones Hue value.
  85431. * 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).
  85432. */
  85433. get: function () {
  85434. return this._midtonesHue;
  85435. },
  85436. /**
  85437. * Sets the midtones Hue value.
  85438. * 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).
  85439. */
  85440. set: function (value) {
  85441. this._midtonesHue = value;
  85442. this._dirty = true;
  85443. },
  85444. enumerable: true,
  85445. configurable: true
  85446. });
  85447. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  85448. /**
  85449. * Gets the midtones Density value.
  85450. * 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.
  85451. * Values less than zero provide a filter of opposite hue.
  85452. */
  85453. get: function () {
  85454. return this._midtonesDensity;
  85455. },
  85456. /**
  85457. * Sets the midtones Density value.
  85458. * 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.
  85459. * Values less than zero provide a filter of opposite hue.
  85460. */
  85461. set: function (value) {
  85462. this._midtonesDensity = value;
  85463. this._dirty = true;
  85464. },
  85465. enumerable: true,
  85466. configurable: true
  85467. });
  85468. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  85469. /**
  85470. * Gets the midtones Saturation value.
  85471. * 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.
  85472. */
  85473. get: function () {
  85474. return this._midtonesSaturation;
  85475. },
  85476. /**
  85477. * Sets the midtones Saturation value.
  85478. * 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.
  85479. */
  85480. set: function (value) {
  85481. this._midtonesSaturation = value;
  85482. this._dirty = true;
  85483. },
  85484. enumerable: true,
  85485. configurable: true
  85486. });
  85487. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  85488. /**
  85489. * Gets the midtones Exposure value.
  85490. * 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.
  85491. */
  85492. get: function () {
  85493. return this._midtonesExposure;
  85494. },
  85495. /**
  85496. * Sets the midtones Exposure value.
  85497. * 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.
  85498. */
  85499. set: function (value) {
  85500. this._midtonesExposure = value;
  85501. this._dirty = true;
  85502. },
  85503. enumerable: true,
  85504. configurable: true
  85505. });
  85506. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  85507. /**
  85508. * Gets the shadows Hue value.
  85509. * 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).
  85510. */
  85511. get: function () {
  85512. return this._shadowsHue;
  85513. },
  85514. /**
  85515. * Sets the shadows Hue value.
  85516. * 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).
  85517. */
  85518. set: function (value) {
  85519. this._shadowsHue = value;
  85520. this._dirty = true;
  85521. },
  85522. enumerable: true,
  85523. configurable: true
  85524. });
  85525. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  85526. /**
  85527. * Gets the shadows Density value.
  85528. * 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.
  85529. * Values less than zero provide a filter of opposite hue.
  85530. */
  85531. get: function () {
  85532. return this._shadowsDensity;
  85533. },
  85534. /**
  85535. * Sets the shadows Density value.
  85536. * 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.
  85537. * Values less than zero provide a filter of opposite hue.
  85538. */
  85539. set: function (value) {
  85540. this._shadowsDensity = value;
  85541. this._dirty = true;
  85542. },
  85543. enumerable: true,
  85544. configurable: true
  85545. });
  85546. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  85547. /**
  85548. * Gets the shadows Saturation value.
  85549. * 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.
  85550. */
  85551. get: function () {
  85552. return this._shadowsSaturation;
  85553. },
  85554. /**
  85555. * Sets the shadows Saturation value.
  85556. * 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.
  85557. */
  85558. set: function (value) {
  85559. this._shadowsSaturation = value;
  85560. this._dirty = true;
  85561. },
  85562. enumerable: true,
  85563. configurable: true
  85564. });
  85565. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  85566. /**
  85567. * Gets the shadows Exposure value.
  85568. * 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.
  85569. */
  85570. get: function () {
  85571. return this._shadowsExposure;
  85572. },
  85573. /**
  85574. * Sets the shadows Exposure value.
  85575. * 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.
  85576. */
  85577. set: function (value) {
  85578. this._shadowsExposure = value;
  85579. this._dirty = true;
  85580. },
  85581. enumerable: true,
  85582. configurable: true
  85583. });
  85584. ColorCurves.prototype.getClassName = function () {
  85585. return "ColorCurves";
  85586. };
  85587. /**
  85588. * Binds the color curves to the shader.
  85589. * @param colorCurves The color curve to bind
  85590. * @param effect The effect to bind to
  85591. */
  85592. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  85593. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  85594. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  85595. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  85596. if (colorCurves._dirty) {
  85597. colorCurves._dirty = false;
  85598. // Fill in global info.
  85599. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  85600. // Compute highlights info.
  85601. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  85602. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  85603. // Compute midtones info.
  85604. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  85605. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  85606. // Compute shadows info.
  85607. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  85608. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  85609. // Compute deltas (neutral is midtones).
  85610. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  85611. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  85612. }
  85613. if (effect) {
  85614. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  85615. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  85616. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  85617. }
  85618. };
  85619. /**
  85620. * Prepare the list of uniforms associated with the ColorCurves effects.
  85621. * @param uniformsList The list of uniforms used in the effect
  85622. */
  85623. ColorCurves.PrepareUniforms = function (uniformsList) {
  85624. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  85625. };
  85626. /**
  85627. * Returns color grading data based on a hue, density, saturation and exposure value.
  85628. * @param filterHue The hue of the color filter.
  85629. * @param filterDensity The density of the color filter.
  85630. * @param saturation The saturation.
  85631. * @param exposure The exposure.
  85632. * @param result The result data container.
  85633. */
  85634. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  85635. if (hue == null) {
  85636. return;
  85637. }
  85638. hue = ColorCurves.clamp(hue, 0, 360);
  85639. density = ColorCurves.clamp(density, -100, 100);
  85640. saturation = ColorCurves.clamp(saturation, -100, 100);
  85641. exposure = ColorCurves.clamp(exposure, -100, 100);
  85642. // Remap the slider/config filter density with non-linear mapping and also scale by half
  85643. // so that the maximum filter density is only 50% control. This provides fine control
  85644. // for small values and reasonable range.
  85645. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  85646. density *= 0.5;
  85647. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  85648. if (density < 0) {
  85649. density *= -1;
  85650. hue = (hue + 180) % 360;
  85651. }
  85652. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  85653. result.scaleToRef(2, result);
  85654. result.a = 1 + 0.01 * saturation;
  85655. };
  85656. /**
  85657. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  85658. * @param value The input slider value in range [-100,100].
  85659. * @returns Adjusted value.
  85660. */
  85661. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  85662. value /= 100;
  85663. var x = Math.abs(value);
  85664. x = Math.pow(x, 2);
  85665. if (value < 0) {
  85666. x *= -1;
  85667. }
  85668. x *= 100;
  85669. return x;
  85670. };
  85671. /**
  85672. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  85673. * @param hue The hue (H) input.
  85674. * @param saturation The saturation (S) input.
  85675. * @param brightness The brightness (B) input.
  85676. * @result An RGBA color represented as Vector4.
  85677. */
  85678. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  85679. var h = ColorCurves.clamp(hue, 0, 360);
  85680. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  85681. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  85682. if (s === 0) {
  85683. result.r = v;
  85684. result.g = v;
  85685. result.b = v;
  85686. }
  85687. else {
  85688. // sector 0 to 5
  85689. h /= 60;
  85690. var i = Math.floor(h);
  85691. // fractional part of h
  85692. var f = h - i;
  85693. var p = v * (1 - s);
  85694. var q = v * (1 - s * f);
  85695. var t = v * (1 - s * (1 - f));
  85696. switch (i) {
  85697. case 0:
  85698. result.r = v;
  85699. result.g = t;
  85700. result.b = p;
  85701. break;
  85702. case 1:
  85703. result.r = q;
  85704. result.g = v;
  85705. result.b = p;
  85706. break;
  85707. case 2:
  85708. result.r = p;
  85709. result.g = v;
  85710. result.b = t;
  85711. break;
  85712. case 3:
  85713. result.r = p;
  85714. result.g = q;
  85715. result.b = v;
  85716. break;
  85717. case 4:
  85718. result.r = t;
  85719. result.g = p;
  85720. result.b = v;
  85721. break;
  85722. default: // case 5:
  85723. result.r = v;
  85724. result.g = p;
  85725. result.b = q;
  85726. break;
  85727. }
  85728. }
  85729. result.a = 1;
  85730. };
  85731. /**
  85732. * Returns a value clamped between min and max
  85733. * @param value The value to clamp
  85734. * @param min The minimum of value
  85735. * @param max The maximum of value
  85736. * @returns The clamped value.
  85737. */
  85738. ColorCurves.clamp = function (value, min, max) {
  85739. return Math.min(Math.max(value, min), max);
  85740. };
  85741. /**
  85742. * Clones the current color curve instance.
  85743. * @return The cloned curves
  85744. */
  85745. ColorCurves.prototype.clone = function () {
  85746. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  85747. };
  85748. /**
  85749. * Serializes the current color curve instance to a json representation.
  85750. * @return a JSON representation
  85751. */
  85752. ColorCurves.prototype.serialize = function () {
  85753. return BABYLON.SerializationHelper.Serialize(this);
  85754. };
  85755. /**
  85756. * Parses the color curve from a json representation.
  85757. * @param source the JSON source to parse
  85758. * @return The parsed curves
  85759. */
  85760. ColorCurves.Parse = function (source) {
  85761. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  85762. };
  85763. __decorate([
  85764. BABYLON.serialize()
  85765. ], ColorCurves.prototype, "_globalHue", void 0);
  85766. __decorate([
  85767. BABYLON.serialize()
  85768. ], ColorCurves.prototype, "_globalDensity", void 0);
  85769. __decorate([
  85770. BABYLON.serialize()
  85771. ], ColorCurves.prototype, "_globalSaturation", void 0);
  85772. __decorate([
  85773. BABYLON.serialize()
  85774. ], ColorCurves.prototype, "_globalExposure", void 0);
  85775. __decorate([
  85776. BABYLON.serialize()
  85777. ], ColorCurves.prototype, "_highlightsHue", void 0);
  85778. __decorate([
  85779. BABYLON.serialize()
  85780. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  85781. __decorate([
  85782. BABYLON.serialize()
  85783. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  85784. __decorate([
  85785. BABYLON.serialize()
  85786. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  85787. __decorate([
  85788. BABYLON.serialize()
  85789. ], ColorCurves.prototype, "_midtonesHue", void 0);
  85790. __decorate([
  85791. BABYLON.serialize()
  85792. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  85793. __decorate([
  85794. BABYLON.serialize()
  85795. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  85796. __decorate([
  85797. BABYLON.serialize()
  85798. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  85799. return ColorCurves;
  85800. }());
  85801. BABYLON.ColorCurves = ColorCurves;
  85802. })(BABYLON || (BABYLON = {}));
  85803. //# sourceMappingURL=babylon.colorCurves.js.map
  85804. var BABYLON;
  85805. (function (BABYLON) {
  85806. var RefractionPostProcess = /** @class */ (function (_super) {
  85807. __extends(RefractionPostProcess, _super);
  85808. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  85809. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  85810. _this.color = color;
  85811. _this.depth = depth;
  85812. _this.colorLevel = colorLevel;
  85813. _this._ownRefractionTexture = true;
  85814. _this.onActivateObservable.add(function (cam) {
  85815. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  85816. });
  85817. _this.onApplyObservable.add(function (effect) {
  85818. effect.setColor3("baseColor", _this.color);
  85819. effect.setFloat("depth", _this.depth);
  85820. effect.setFloat("colorLevel", _this.colorLevel);
  85821. effect.setTexture("refractionSampler", _this._refTexture);
  85822. });
  85823. return _this;
  85824. }
  85825. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  85826. /**
  85827. * Gets or sets the refraction texture
  85828. * Please note that you are responsible for disposing the texture if you set it manually
  85829. */
  85830. get: function () {
  85831. return this._refTexture;
  85832. },
  85833. set: function (value) {
  85834. if (this._refTexture && this._ownRefractionTexture) {
  85835. this._refTexture.dispose();
  85836. }
  85837. this._refTexture = value;
  85838. this._ownRefractionTexture = false;
  85839. },
  85840. enumerable: true,
  85841. configurable: true
  85842. });
  85843. // Methods
  85844. RefractionPostProcess.prototype.dispose = function (camera) {
  85845. if (this._refTexture && this._ownRefractionTexture) {
  85846. this._refTexture.dispose();
  85847. this._refTexture = null;
  85848. }
  85849. _super.prototype.dispose.call(this, camera);
  85850. };
  85851. return RefractionPostProcess;
  85852. }(BABYLON.PostProcess));
  85853. BABYLON.RefractionPostProcess = RefractionPostProcess;
  85854. })(BABYLON || (BABYLON = {}));
  85855. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  85856. var BABYLON;
  85857. (function (BABYLON) {
  85858. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  85859. __extends(BlackAndWhitePostProcess, _super);
  85860. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  85861. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  85862. _this.degree = 1;
  85863. _this.onApplyObservable.add(function (effect) {
  85864. effect.setFloat("degree", _this.degree);
  85865. });
  85866. return _this;
  85867. }
  85868. return BlackAndWhitePostProcess;
  85869. }(BABYLON.PostProcess));
  85870. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  85871. })(BABYLON || (BABYLON = {}));
  85872. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  85873. var BABYLON;
  85874. (function (BABYLON) {
  85875. /**
  85876. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  85877. * input texture to perform effects such as edge detection or sharpening
  85878. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85879. */
  85880. var ConvolutionPostProcess = /** @class */ (function (_super) {
  85881. __extends(ConvolutionPostProcess, _super);
  85882. /**
  85883. * Creates a new instance ConvolutionPostProcess
  85884. * @param name The name of the effect.
  85885. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  85886. * @param options The required width/height ratio to downsize to before computing the render pass.
  85887. * @param camera The camera to apply the render pass to.
  85888. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85889. * @param engine The engine which the post process will be applied. (default: current engine)
  85890. * @param reusable If the post process can be reused on the same frame. (default: false)
  85891. * @param textureType Type of textures used when performing the post process. (default: 0)
  85892. */
  85893. function ConvolutionPostProcess(name,
  85894. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  85895. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  85896. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85897. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85898. _this.kernel = kernel;
  85899. _this.onApply = function (effect) {
  85900. effect.setFloat2("screenSize", _this.width, _this.height);
  85901. effect.setArray("kernel", _this.kernel);
  85902. };
  85903. return _this;
  85904. }
  85905. // Statics
  85906. /**
  85907. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85908. */
  85909. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  85910. /**
  85911. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85912. */
  85913. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  85914. /**
  85915. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85916. */
  85917. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  85918. /**
  85919. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85920. */
  85921. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  85922. /**
  85923. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85924. */
  85925. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  85926. /**
  85927. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  85928. */
  85929. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  85930. return ConvolutionPostProcess;
  85931. }(BABYLON.PostProcess));
  85932. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85933. })(BABYLON || (BABYLON = {}));
  85934. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85935. var BABYLON;
  85936. (function (BABYLON) {
  85937. var FilterPostProcess = /** @class */ (function (_super) {
  85938. __extends(FilterPostProcess, _super);
  85939. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85940. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85941. _this.kernelMatrix = kernelMatrix;
  85942. _this.onApply = function (effect) {
  85943. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85944. };
  85945. return _this;
  85946. }
  85947. return FilterPostProcess;
  85948. }(BABYLON.PostProcess));
  85949. BABYLON.FilterPostProcess = FilterPostProcess;
  85950. })(BABYLON || (BABYLON = {}));
  85951. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85952. var BABYLON;
  85953. (function (BABYLON) {
  85954. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85955. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85956. __extends(VolumetricLightScatteringPostProcess, _super);
  85957. /**
  85958. * @constructor
  85959. * @param {string} name - The post-process name
  85960. * @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)
  85961. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85962. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85963. * @param {number} samples - The post-process quality, default 100
  85964. * @param {number} samplingMode - The post-process filtering mode
  85965. * @param {BABYLON.Engine} engine - The babylon engine
  85966. * @param {boolean} reusable - If the post-process is reusable
  85967. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85968. */
  85969. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85970. if (samples === void 0) { samples = 100; }
  85971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85972. 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;
  85973. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85974. /**
  85975. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85976. */
  85977. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85978. /**
  85979. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85980. */
  85981. _this.useCustomMeshPosition = false;
  85982. /**
  85983. * If the post-process should inverse the light scattering direction
  85984. */
  85985. _this.invert = true;
  85986. /**
  85987. * Array containing the excluded meshes not rendered in the internal pass
  85988. */
  85989. _this.excludedMeshes = new Array();
  85990. /**
  85991. * Controls the overall intensity of the post-process
  85992. */
  85993. _this.exposure = 0.3;
  85994. /**
  85995. * Dissipates each sample's contribution in range [0, 1]
  85996. */
  85997. _this.decay = 0.96815;
  85998. /**
  85999. * Controls the overall intensity of each sample
  86000. */
  86001. _this.weight = 0.58767;
  86002. /**
  86003. * Controls the density of each sample
  86004. */
  86005. _this.density = 0.926;
  86006. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  86007. engine = scene.getEngine();
  86008. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  86009. // Configure mesh
  86010. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  86011. // Configure
  86012. _this._createPass(scene, ratio.passRatio || ratio);
  86013. _this.onActivate = function (camera) {
  86014. if (!_this.isSupported) {
  86015. _this.dispose(camera);
  86016. }
  86017. _this.onActivate = null;
  86018. };
  86019. _this.onApplyObservable.add(function (effect) {
  86020. _this._updateMeshScreenCoordinates(scene);
  86021. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  86022. effect.setFloat("exposure", _this.exposure);
  86023. effect.setFloat("decay", _this.decay);
  86024. effect.setFloat("weight", _this.weight);
  86025. effect.setFloat("density", _this.density);
  86026. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  86027. });
  86028. return _this;
  86029. }
  86030. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  86031. get: function () {
  86032. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86033. return false;
  86034. },
  86035. set: function (useDiffuseColor) {
  86036. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  86037. },
  86038. enumerable: true,
  86039. configurable: true
  86040. });
  86041. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  86042. return "VolumetricLightScatteringPostProcess";
  86043. };
  86044. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  86045. var mesh = subMesh.getMesh();
  86046. // Render this.mesh as default
  86047. if (mesh === this.mesh && mesh.material) {
  86048. return mesh.material.isReady(mesh);
  86049. }
  86050. var defines = [];
  86051. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86052. var material = subMesh.getMaterial();
  86053. // Alpha test
  86054. if (material) {
  86055. if (material.needAlphaTesting()) {
  86056. defines.push("#define ALPHATEST");
  86057. }
  86058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86059. attribs.push(BABYLON.VertexBuffer.UVKind);
  86060. defines.push("#define UV1");
  86061. }
  86062. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86063. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86064. defines.push("#define UV2");
  86065. }
  86066. }
  86067. // Bones
  86068. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86069. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86070. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86071. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86072. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86073. }
  86074. else {
  86075. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86076. }
  86077. // Instances
  86078. if (useInstances) {
  86079. defines.push("#define INSTANCES");
  86080. attribs.push("world0");
  86081. attribs.push("world1");
  86082. attribs.push("world2");
  86083. attribs.push("world3");
  86084. }
  86085. // Get correct effect
  86086. var join = defines.join("\n");
  86087. if (this._cachedDefines !== join) {
  86088. this._cachedDefines = join;
  86089. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  86090. }
  86091. return this._volumetricLightScatteringPass.isReady();
  86092. };
  86093. /**
  86094. * Sets the new light position for light scattering effect
  86095. * @param {BABYLON.Vector3} The new custom light position
  86096. */
  86097. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  86098. this.customMeshPosition = position;
  86099. };
  86100. /**
  86101. * Returns the light position for light scattering effect
  86102. * @return {BABYLON.Vector3} The custom light position
  86103. */
  86104. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  86105. return this.customMeshPosition;
  86106. };
  86107. /**
  86108. * Disposes the internal assets and detaches the post-process from the camera
  86109. */
  86110. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  86111. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  86112. if (rttIndex !== -1) {
  86113. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  86114. }
  86115. this._volumetricLightScatteringRTT.dispose();
  86116. _super.prototype.dispose.call(this, camera);
  86117. };
  86118. /**
  86119. * Returns the render target texture used by the post-process
  86120. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  86121. */
  86122. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  86123. return this._volumetricLightScatteringRTT;
  86124. };
  86125. // Private methods
  86126. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  86127. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  86128. return true;
  86129. }
  86130. return false;
  86131. };
  86132. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  86133. var _this = this;
  86134. var engine = scene.getEngine();
  86135. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86136. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86137. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86138. this._volumetricLightScatteringRTT.renderList = null;
  86139. this._volumetricLightScatteringRTT.renderParticles = false;
  86140. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  86141. var camera = this.getCamera();
  86142. if (camera) {
  86143. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86144. }
  86145. else {
  86146. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  86147. }
  86148. // Custom render function for submeshes
  86149. var renderSubMesh = function (subMesh) {
  86150. var mesh = subMesh.getRenderingMesh();
  86151. if (_this._meshExcluded(mesh)) {
  86152. return;
  86153. }
  86154. var material = subMesh.getMaterial();
  86155. if (!material) {
  86156. return;
  86157. }
  86158. var scene = mesh.getScene();
  86159. var engine = scene.getEngine();
  86160. // Culling
  86161. engine.setState(material.backFaceCulling);
  86162. // Managing instances
  86163. var batch = mesh._getInstancesRenderList(subMesh._id);
  86164. if (batch.mustReturn) {
  86165. return;
  86166. }
  86167. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  86168. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  86169. var effect = _this._volumetricLightScatteringPass;
  86170. if (mesh === _this.mesh) {
  86171. if (subMesh.effect) {
  86172. effect = subMesh.effect;
  86173. }
  86174. else {
  86175. effect = material.getEffect();
  86176. }
  86177. }
  86178. engine.enableEffect(effect);
  86179. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  86180. if (mesh === _this.mesh) {
  86181. material.bind(mesh.getWorldMatrix(), mesh);
  86182. }
  86183. else {
  86184. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  86185. // Alpha test
  86186. if (material && material.needAlphaTesting()) {
  86187. var alphaTexture = material.getAlphaTestTexture();
  86188. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  86189. if (alphaTexture) {
  86190. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86191. }
  86192. }
  86193. // Bones
  86194. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86195. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86196. }
  86197. }
  86198. // Draw
  86199. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  86200. }
  86201. };
  86202. // Render target texture callbacks
  86203. var savedSceneClearColor;
  86204. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  86205. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  86206. savedSceneClearColor = scene.clearColor;
  86207. scene.clearColor = sceneClearColor;
  86208. });
  86209. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  86210. scene.clearColor = savedSceneClearColor;
  86211. });
  86212. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86213. var engine = scene.getEngine();
  86214. var index;
  86215. if (depthOnlySubMeshes.length) {
  86216. engine.setColorWrite(false);
  86217. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86218. renderSubMesh(depthOnlySubMeshes.data[index]);
  86219. }
  86220. engine.setColorWrite(true);
  86221. }
  86222. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86223. renderSubMesh(opaqueSubMeshes.data[index]);
  86224. }
  86225. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86226. renderSubMesh(alphaTestSubMeshes.data[index]);
  86227. }
  86228. if (transparentSubMeshes.length) {
  86229. // Sort sub meshes
  86230. for (index = 0; index < transparentSubMeshes.length; index++) {
  86231. var submesh = transparentSubMeshes.data[index];
  86232. var boundingInfo = submesh.getBoundingInfo();
  86233. if (boundingInfo && scene.activeCamera) {
  86234. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  86235. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  86236. }
  86237. }
  86238. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  86239. sortedArray.sort(function (a, b) {
  86240. // Alpha index first
  86241. if (a._alphaIndex > b._alphaIndex) {
  86242. return 1;
  86243. }
  86244. if (a._alphaIndex < b._alphaIndex) {
  86245. return -1;
  86246. }
  86247. // Then distance to camera
  86248. if (a._distanceToCamera < b._distanceToCamera) {
  86249. return 1;
  86250. }
  86251. if (a._distanceToCamera > b._distanceToCamera) {
  86252. return -1;
  86253. }
  86254. return 0;
  86255. });
  86256. // Render sub meshes
  86257. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  86258. for (index = 0; index < sortedArray.length; index++) {
  86259. renderSubMesh(sortedArray[index]);
  86260. }
  86261. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86262. }
  86263. };
  86264. };
  86265. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  86266. var transform = scene.getTransformMatrix();
  86267. var meshPosition;
  86268. if (this.useCustomMeshPosition) {
  86269. meshPosition = this.customMeshPosition;
  86270. }
  86271. else if (this.attachedNode) {
  86272. meshPosition = this.attachedNode.position;
  86273. }
  86274. else {
  86275. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  86276. }
  86277. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  86278. this._screenCoordinates.x = pos.x / this._viewPort.width;
  86279. this._screenCoordinates.y = pos.y / this._viewPort.height;
  86280. if (this.invert)
  86281. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  86282. };
  86283. // Static methods
  86284. /**
  86285. * Creates a default mesh for the Volumeric Light Scattering post-process
  86286. * @param {string} The mesh name
  86287. * @param {BABYLON.Scene} The scene where to create the mesh
  86288. * @return {BABYLON.Mesh} the default mesh
  86289. */
  86290. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  86291. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  86292. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  86293. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  86294. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  86295. mesh.material = material;
  86296. return mesh;
  86297. };
  86298. __decorate([
  86299. BABYLON.serializeAsVector3()
  86300. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  86301. __decorate([
  86302. BABYLON.serialize()
  86303. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  86304. __decorate([
  86305. BABYLON.serialize()
  86306. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  86307. __decorate([
  86308. BABYLON.serializeAsMeshReference()
  86309. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  86310. __decorate([
  86311. BABYLON.serialize()
  86312. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  86313. __decorate([
  86314. BABYLON.serialize()
  86315. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  86316. __decorate([
  86317. BABYLON.serialize()
  86318. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  86319. __decorate([
  86320. BABYLON.serialize()
  86321. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  86322. __decorate([
  86323. BABYLON.serialize()
  86324. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  86325. return VolumetricLightScatteringPostProcess;
  86326. }(BABYLON.PostProcess));
  86327. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  86328. })(BABYLON || (BABYLON = {}));
  86329. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  86330. //
  86331. // This post-process allows the modification of rendered colors by using
  86332. // a 'look-up table' (LUT). This effect is also called Color Grading.
  86333. //
  86334. // The object needs to be provided an url to a texture containing the color
  86335. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  86336. // Use an image editing software to tweak the LUT to match your needs.
  86337. //
  86338. // For an example of a color LUT, see here:
  86339. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  86340. // For explanations on color grading, see here:
  86341. // http://udn.epicgames.com/Three/ColorGrading.html
  86342. //
  86343. var BABYLON;
  86344. (function (BABYLON) {
  86345. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  86346. __extends(ColorCorrectionPostProcess, _super);
  86347. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  86348. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  86349. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86350. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  86351. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86352. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86353. _this.onApply = function (effect) {
  86354. effect.setTexture("colorTable", _this._colorTableTexture);
  86355. };
  86356. return _this;
  86357. }
  86358. return ColorCorrectionPostProcess;
  86359. }(BABYLON.PostProcess));
  86360. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  86361. })(BABYLON || (BABYLON = {}));
  86362. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  86363. var BABYLON;
  86364. (function (BABYLON) {
  86365. /** Defines operator used for tonemapping */
  86366. var TonemappingOperator;
  86367. (function (TonemappingOperator) {
  86368. /** Hable */
  86369. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  86370. /** Reinhard */
  86371. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  86372. /** HejiDawson */
  86373. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  86374. /** Photographic */
  86375. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  86376. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  86377. ;
  86378. /**
  86379. * Defines a post process to apply tone mapping
  86380. */
  86381. var TonemapPostProcess = /** @class */ (function (_super) {
  86382. __extends(TonemapPostProcess, _super);
  86383. /**
  86384. * Creates a new TonemapPostProcess
  86385. * @param name defines the name of the postprocess
  86386. * @param _operator defines the operator to use
  86387. * @param exposureAdjustment defines the required exposure adjustement
  86388. * @param camera defines the camera to use (can be null)
  86389. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  86390. * @param engine defines the hosting engine (can be ignore if camera is set)
  86391. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  86392. */
  86393. function TonemapPostProcess(name, _operator,
  86394. /** Defines the required exposure adjustement */
  86395. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  86396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86397. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86398. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  86399. _this._operator = _operator;
  86400. _this.exposureAdjustment = exposureAdjustment;
  86401. var defines = "#define ";
  86402. if (_this._operator === TonemappingOperator.Hable)
  86403. defines += "HABLE_TONEMAPPING";
  86404. else if (_this._operator === TonemappingOperator.Reinhard)
  86405. defines += "REINHARD_TONEMAPPING";
  86406. else if (_this._operator === TonemappingOperator.HejiDawson)
  86407. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  86408. else if (_this._operator === TonemappingOperator.Photographic)
  86409. defines += "PHOTOGRAPHIC_TONEMAPPING";
  86410. //sadly a second call to create the effect.
  86411. _this.updateEffect(defines);
  86412. _this.onApply = function (effect) {
  86413. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  86414. };
  86415. return _this;
  86416. }
  86417. return TonemapPostProcess;
  86418. }(BABYLON.PostProcess));
  86419. BABYLON.TonemapPostProcess = TonemapPostProcess;
  86420. })(BABYLON || (BABYLON = {}));
  86421. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  86422. var BABYLON;
  86423. (function (BABYLON) {
  86424. var DisplayPassPostProcess = /** @class */ (function (_super) {
  86425. __extends(DisplayPassPostProcess, _super);
  86426. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  86427. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  86428. }
  86429. return DisplayPassPostProcess;
  86430. }(BABYLON.PostProcess));
  86431. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  86432. })(BABYLON || (BABYLON = {}));
  86433. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  86434. var BABYLON;
  86435. (function (BABYLON) {
  86436. var HighlightsPostProcess = /** @class */ (function (_super) {
  86437. __extends(HighlightsPostProcess, _super);
  86438. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  86439. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86440. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  86441. }
  86442. return HighlightsPostProcess;
  86443. }(BABYLON.PostProcess));
  86444. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  86445. })(BABYLON || (BABYLON = {}));
  86446. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  86447. var BABYLON;
  86448. (function (BABYLON) {
  86449. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  86450. __extends(ImageProcessingPostProcess, _super);
  86451. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  86452. if (camera === void 0) { camera = null; }
  86453. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86454. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  86455. _this._fromLinearSpace = true;
  86456. /**
  86457. * Defines cache preventing GC.
  86458. */
  86459. _this._defines = {
  86460. IMAGEPROCESSING: false,
  86461. VIGNETTE: false,
  86462. VIGNETTEBLENDMODEMULTIPLY: false,
  86463. VIGNETTEBLENDMODEOPAQUE: false,
  86464. TONEMAPPING: false,
  86465. TONEMAPPING_ACES: false,
  86466. CONTRAST: false,
  86467. COLORCURVES: false,
  86468. COLORGRADING: false,
  86469. COLORGRADING3D: false,
  86470. FROMLINEARSPACE: false,
  86471. SAMPLER3DGREENDEPTH: false,
  86472. SAMPLER3DBGRMAP: false,
  86473. IMAGEPROCESSINGPOSTPROCESS: false,
  86474. EXPOSURE: false,
  86475. };
  86476. // Setup the configuration as forced by the constructor. This would then not force the
  86477. // scene materials output in linear space and let untouched the default forward pass.
  86478. if (imageProcessingConfiguration) {
  86479. imageProcessingConfiguration.applyByPostProcess = true;
  86480. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  86481. // This will cause the shader to be compiled
  86482. _this.fromLinearSpace = false;
  86483. }
  86484. // Setup the default processing configuration to the scene.
  86485. else {
  86486. _this._attachImageProcessingConfiguration(null, true);
  86487. _this.imageProcessingConfiguration.applyByPostProcess = true;
  86488. }
  86489. _this.onApply = function (effect) {
  86490. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  86491. };
  86492. return _this;
  86493. }
  86494. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  86495. /**
  86496. * Gets the image processing configuration used either in this material.
  86497. */
  86498. get: function () {
  86499. return this._imageProcessingConfiguration;
  86500. },
  86501. /**
  86502. * Sets the Default image processing configuration used either in the this material.
  86503. *
  86504. * If sets to null, the scene one is in use.
  86505. */
  86506. set: function (value) {
  86507. this._attachImageProcessingConfiguration(value);
  86508. },
  86509. enumerable: true,
  86510. configurable: true
  86511. });
  86512. /**
  86513. * Attaches a new image processing configuration to the PBR Material.
  86514. * @param configuration
  86515. */
  86516. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  86517. var _this = this;
  86518. if (doNotBuild === void 0) { doNotBuild = false; }
  86519. if (configuration === this._imageProcessingConfiguration) {
  86520. return;
  86521. }
  86522. // Detaches observer.
  86523. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86524. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86525. }
  86526. // Pick the scene configuration if needed.
  86527. if (!configuration) {
  86528. var scene = null;
  86529. var engine = this.getEngine();
  86530. var camera = this.getCamera();
  86531. if (camera) {
  86532. scene = camera.getScene();
  86533. }
  86534. else if (engine && engine.scenes) {
  86535. var scenes = engine.scenes;
  86536. scene = scenes[scenes.length - 1];
  86537. }
  86538. else {
  86539. scene = BABYLON.Engine.LastCreatedScene;
  86540. }
  86541. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  86542. }
  86543. else {
  86544. this._imageProcessingConfiguration = configuration;
  86545. }
  86546. // Attaches observer.
  86547. if (this._imageProcessingConfiguration) {
  86548. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86549. _this._updateParameters();
  86550. });
  86551. }
  86552. // Ensure the effect will be rebuilt.
  86553. if (!doNotBuild) {
  86554. this._updateParameters();
  86555. }
  86556. };
  86557. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  86558. /**
  86559. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86560. */
  86561. get: function () {
  86562. return this.imageProcessingConfiguration.colorCurves;
  86563. },
  86564. /**
  86565. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  86566. */
  86567. set: function (value) {
  86568. this.imageProcessingConfiguration.colorCurves = value;
  86569. },
  86570. enumerable: true,
  86571. configurable: true
  86572. });
  86573. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  86574. /**
  86575. * Gets wether the color curves effect is enabled.
  86576. */
  86577. get: function () {
  86578. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86579. },
  86580. /**
  86581. * Sets wether the color curves effect is enabled.
  86582. */
  86583. set: function (value) {
  86584. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  86585. },
  86586. enumerable: true,
  86587. configurable: true
  86588. });
  86589. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  86590. /**
  86591. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86592. */
  86593. get: function () {
  86594. return this.imageProcessingConfiguration.colorGradingTexture;
  86595. },
  86596. /**
  86597. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  86598. */
  86599. set: function (value) {
  86600. this.imageProcessingConfiguration.colorGradingTexture = value;
  86601. },
  86602. enumerable: true,
  86603. configurable: true
  86604. });
  86605. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  86606. /**
  86607. * Gets wether the color grading effect is enabled.
  86608. */
  86609. get: function () {
  86610. return this.imageProcessingConfiguration.colorGradingEnabled;
  86611. },
  86612. /**
  86613. * Gets wether the color grading effect is enabled.
  86614. */
  86615. set: function (value) {
  86616. this.imageProcessingConfiguration.colorGradingEnabled = value;
  86617. },
  86618. enumerable: true,
  86619. configurable: true
  86620. });
  86621. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  86622. /**
  86623. * Gets exposure used in the effect.
  86624. */
  86625. get: function () {
  86626. return this.imageProcessingConfiguration.exposure;
  86627. },
  86628. /**
  86629. * Sets exposure used in the effect.
  86630. */
  86631. set: function (value) {
  86632. this.imageProcessingConfiguration.exposure = value;
  86633. },
  86634. enumerable: true,
  86635. configurable: true
  86636. });
  86637. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  86638. /**
  86639. * Gets wether tonemapping is enabled or not.
  86640. */
  86641. get: function () {
  86642. return this._imageProcessingConfiguration.toneMappingEnabled;
  86643. },
  86644. /**
  86645. * Sets wether tonemapping is enabled or not
  86646. */
  86647. set: function (value) {
  86648. this._imageProcessingConfiguration.toneMappingEnabled = value;
  86649. },
  86650. enumerable: true,
  86651. configurable: true
  86652. });
  86653. ;
  86654. ;
  86655. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  86656. /**
  86657. * Gets contrast used in the effect.
  86658. */
  86659. get: function () {
  86660. return this.imageProcessingConfiguration.contrast;
  86661. },
  86662. /**
  86663. * Sets contrast used in the effect.
  86664. */
  86665. set: function (value) {
  86666. this.imageProcessingConfiguration.contrast = value;
  86667. },
  86668. enumerable: true,
  86669. configurable: true
  86670. });
  86671. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  86672. /**
  86673. * Gets Vignette stretch size.
  86674. */
  86675. get: function () {
  86676. return this.imageProcessingConfiguration.vignetteStretch;
  86677. },
  86678. /**
  86679. * Sets Vignette stretch size.
  86680. */
  86681. set: function (value) {
  86682. this.imageProcessingConfiguration.vignetteStretch = value;
  86683. },
  86684. enumerable: true,
  86685. configurable: true
  86686. });
  86687. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  86688. /**
  86689. * Gets Vignette centre X Offset.
  86690. */
  86691. get: function () {
  86692. return this.imageProcessingConfiguration.vignetteCentreX;
  86693. },
  86694. /**
  86695. * Sets Vignette centre X Offset.
  86696. */
  86697. set: function (value) {
  86698. this.imageProcessingConfiguration.vignetteCentreX = value;
  86699. },
  86700. enumerable: true,
  86701. configurable: true
  86702. });
  86703. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  86704. /**
  86705. * Gets Vignette centre Y Offset.
  86706. */
  86707. get: function () {
  86708. return this.imageProcessingConfiguration.vignetteCentreY;
  86709. },
  86710. /**
  86711. * Sets Vignette centre Y Offset.
  86712. */
  86713. set: function (value) {
  86714. this.imageProcessingConfiguration.vignetteCentreY = value;
  86715. },
  86716. enumerable: true,
  86717. configurable: true
  86718. });
  86719. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  86720. /**
  86721. * Gets Vignette weight or intensity of the vignette effect.
  86722. */
  86723. get: function () {
  86724. return this.imageProcessingConfiguration.vignetteWeight;
  86725. },
  86726. /**
  86727. * Sets Vignette weight or intensity of the vignette effect.
  86728. */
  86729. set: function (value) {
  86730. this.imageProcessingConfiguration.vignetteWeight = value;
  86731. },
  86732. enumerable: true,
  86733. configurable: true
  86734. });
  86735. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  86736. /**
  86737. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86738. * if vignetteEnabled is set to true.
  86739. */
  86740. get: function () {
  86741. return this.imageProcessingConfiguration.vignetteColor;
  86742. },
  86743. /**
  86744. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86745. * if vignetteEnabled is set to true.
  86746. */
  86747. set: function (value) {
  86748. this.imageProcessingConfiguration.vignetteColor = value;
  86749. },
  86750. enumerable: true,
  86751. configurable: true
  86752. });
  86753. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  86754. /**
  86755. * Gets Camera field of view used by the Vignette effect.
  86756. */
  86757. get: function () {
  86758. return this.imageProcessingConfiguration.vignetteCameraFov;
  86759. },
  86760. /**
  86761. * Sets Camera field of view used by the Vignette effect.
  86762. */
  86763. set: function (value) {
  86764. this.imageProcessingConfiguration.vignetteCameraFov = value;
  86765. },
  86766. enumerable: true,
  86767. configurable: true
  86768. });
  86769. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  86770. /**
  86771. * Gets the vignette blend mode allowing different kind of effect.
  86772. */
  86773. get: function () {
  86774. return this.imageProcessingConfiguration.vignetteBlendMode;
  86775. },
  86776. /**
  86777. * Sets the vignette blend mode allowing different kind of effect.
  86778. */
  86779. set: function (value) {
  86780. this.imageProcessingConfiguration.vignetteBlendMode = value;
  86781. },
  86782. enumerable: true,
  86783. configurable: true
  86784. });
  86785. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  86786. /**
  86787. * Gets wether the vignette effect is enabled.
  86788. */
  86789. get: function () {
  86790. return this.imageProcessingConfiguration.vignetteEnabled;
  86791. },
  86792. /**
  86793. * Sets wether the vignette effect is enabled.
  86794. */
  86795. set: function (value) {
  86796. this.imageProcessingConfiguration.vignetteEnabled = value;
  86797. },
  86798. enumerable: true,
  86799. configurable: true
  86800. });
  86801. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  86802. /**
  86803. * Gets wether the input of the processing is in Gamma or Linear Space.
  86804. */
  86805. get: function () {
  86806. return this._fromLinearSpace;
  86807. },
  86808. /**
  86809. * Sets wether the input of the processing is in Gamma or Linear Space.
  86810. */
  86811. set: function (value) {
  86812. if (this._fromLinearSpace === value) {
  86813. return;
  86814. }
  86815. this._fromLinearSpace = value;
  86816. this._updateParameters();
  86817. },
  86818. enumerable: true,
  86819. configurable: true
  86820. });
  86821. ImageProcessingPostProcess.prototype.getClassName = function () {
  86822. return "ImageProcessingPostProcess";
  86823. };
  86824. ImageProcessingPostProcess.prototype._updateParameters = function () {
  86825. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  86826. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  86827. var defines = "";
  86828. for (var define in this._defines) {
  86829. if (this._defines[define]) {
  86830. defines += "#define " + define + ";\r\n";
  86831. }
  86832. }
  86833. var samplers = ["textureSampler"];
  86834. var uniforms = ["scale"];
  86835. if (BABYLON.ImageProcessingConfiguration) {
  86836. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  86837. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  86838. }
  86839. this.updateEffect(defines, uniforms, samplers);
  86840. };
  86841. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  86842. _super.prototype.dispose.call(this, camera);
  86843. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86844. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86845. }
  86846. if (this._imageProcessingConfiguration) {
  86847. this.imageProcessingConfiguration.applyByPostProcess = false;
  86848. }
  86849. };
  86850. __decorate([
  86851. BABYLON.serialize()
  86852. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  86853. return ImageProcessingPostProcess;
  86854. }(BABYLON.PostProcess));
  86855. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  86856. })(BABYLON || (BABYLON = {}));
  86857. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  86858. var BABYLON;
  86859. (function (BABYLON) {
  86860. /**
  86861. * Class used to store bone information
  86862. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  86863. */
  86864. var Bone = /** @class */ (function (_super) {
  86865. __extends(Bone, _super);
  86866. /**
  86867. * Create a new bone
  86868. * @param name defines the bone name
  86869. * @param skeleton defines the parent skeleton
  86870. * @param parentBone defines the parent (can be null if the bone is the root)
  86871. * @param localMatrix defines the local matrix
  86872. * @param restPose defines the rest pose matrix
  86873. * @param baseMatrix defines the base matrix
  86874. * @param index defines index of the bone in the hiearchy
  86875. */
  86876. function Bone(
  86877. /**
  86878. * defines the bone name
  86879. */
  86880. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  86881. if (parentBone === void 0) { parentBone = null; }
  86882. if (localMatrix === void 0) { localMatrix = null; }
  86883. if (restPose === void 0) { restPose = null; }
  86884. if (baseMatrix === void 0) { baseMatrix = null; }
  86885. if (index === void 0) { index = null; }
  86886. var _this = _super.call(this, name, skeleton.getScene()) || this;
  86887. _this.name = name;
  86888. /**
  86889. * Gets the list of child bones
  86890. */
  86891. _this.children = new Array();
  86892. /** Gets the animations associated with this bone */
  86893. _this.animations = new Array();
  86894. /**
  86895. * @hidden Internal only
  86896. * Set this value to map this bone to a different index in the transform matrices
  86897. * Set this value to -1 to exclude the bone from the transform matrices
  86898. */
  86899. _this._index = null;
  86900. _this._absoluteTransform = new BABYLON.Matrix();
  86901. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  86902. _this._scalingDeterminant = 1;
  86903. _this._worldTransform = new BABYLON.Matrix();
  86904. _this._needToDecompose = true;
  86905. _this._needToCompose = false;
  86906. _this._skeleton = skeleton;
  86907. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  86908. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  86909. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  86910. _this._index = index;
  86911. skeleton.bones.push(_this);
  86912. _this.setParent(parentBone, false);
  86913. if (baseMatrix || localMatrix) {
  86914. _this._updateDifferenceMatrix();
  86915. }
  86916. return _this;
  86917. }
  86918. Object.defineProperty(Bone.prototype, "_matrix", {
  86919. /** @hidden */
  86920. get: function () {
  86921. this._compose();
  86922. return this._localMatrix;
  86923. },
  86924. /** @hidden */
  86925. set: function (value) {
  86926. this._localMatrix.copyFrom(value);
  86927. this._needToDecompose = true;
  86928. },
  86929. enumerable: true,
  86930. configurable: true
  86931. });
  86932. // Members
  86933. /**
  86934. * Gets the parent skeleton
  86935. * @returns a skeleton
  86936. */
  86937. Bone.prototype.getSkeleton = function () {
  86938. return this._skeleton;
  86939. };
  86940. /**
  86941. * Gets parent bone
  86942. * @returns a bone or null if the bone is the root of the bone hierarchy
  86943. */
  86944. Bone.prototype.getParent = function () {
  86945. return this._parent;
  86946. };
  86947. /**
  86948. * Sets the parent bone
  86949. * @param parent defines the parent (can be null if the bone is the root)
  86950. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86951. */
  86952. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86953. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86954. if (this._parent === parent) {
  86955. return;
  86956. }
  86957. if (this._parent) {
  86958. var index = this._parent.children.indexOf(this);
  86959. if (index !== -1) {
  86960. this._parent.children.splice(index, 1);
  86961. }
  86962. }
  86963. this._parent = parent;
  86964. if (this._parent) {
  86965. this._parent.children.push(this);
  86966. }
  86967. if (updateDifferenceMatrix) {
  86968. this._updateDifferenceMatrix();
  86969. }
  86970. this.markAsDirty();
  86971. };
  86972. /**
  86973. * Gets the local matrix
  86974. * @returns a matrix
  86975. */
  86976. Bone.prototype.getLocalMatrix = function () {
  86977. this._compose();
  86978. return this._localMatrix;
  86979. };
  86980. /**
  86981. * Gets the base matrix (initial matrix which remains unchanged)
  86982. * @returns a matrix
  86983. */
  86984. Bone.prototype.getBaseMatrix = function () {
  86985. return this._baseMatrix;
  86986. };
  86987. /**
  86988. * Gets the rest pose matrix
  86989. * @returns a matrix
  86990. */
  86991. Bone.prototype.getRestPose = function () {
  86992. return this._restPose;
  86993. };
  86994. /**
  86995. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86996. */
  86997. Bone.prototype.getWorldMatrix = function () {
  86998. return this._worldTransform;
  86999. };
  87000. /**
  87001. * Sets the local matrix to rest pose matrix
  87002. */
  87003. Bone.prototype.returnToRest = function () {
  87004. this.updateMatrix(this._restPose.clone());
  87005. };
  87006. /**
  87007. * Gets the inverse of the absolute transform matrix.
  87008. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  87009. * @returns a matrix
  87010. */
  87011. Bone.prototype.getInvertedAbsoluteTransform = function () {
  87012. return this._invertedAbsoluteTransform;
  87013. };
  87014. /**
  87015. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  87016. * @returns a matrix
  87017. */
  87018. Bone.prototype.getAbsoluteTransform = function () {
  87019. return this._absoluteTransform;
  87020. };
  87021. Object.defineProperty(Bone.prototype, "position", {
  87022. // Properties (matches AbstractMesh properties)
  87023. /** Gets or sets current position (in local space) */
  87024. get: function () {
  87025. this._decompose();
  87026. return this._localPosition;
  87027. },
  87028. set: function (newPosition) {
  87029. this._decompose();
  87030. this._localPosition.copyFrom(newPosition);
  87031. this._markAsDirtyAndCompose();
  87032. },
  87033. enumerable: true,
  87034. configurable: true
  87035. });
  87036. Object.defineProperty(Bone.prototype, "rotation", {
  87037. /** Gets or sets current rotation (in local space) */
  87038. get: function () {
  87039. return this.getRotation();
  87040. },
  87041. set: function (newRotation) {
  87042. this.setRotation(newRotation);
  87043. },
  87044. enumerable: true,
  87045. configurable: true
  87046. });
  87047. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  87048. /** Gets or sets current rotation quaternion (in local space) */
  87049. get: function () {
  87050. this._decompose();
  87051. return this._localRotation;
  87052. },
  87053. set: function (newRotation) {
  87054. this.setRotationQuaternion(newRotation);
  87055. },
  87056. enumerable: true,
  87057. configurable: true
  87058. });
  87059. Object.defineProperty(Bone.prototype, "scaling", {
  87060. /** Gets or sets current scaling (in local space) */
  87061. get: function () {
  87062. return this.getScale();
  87063. },
  87064. set: function (newScaling) {
  87065. this.setScale(newScaling);
  87066. },
  87067. enumerable: true,
  87068. configurable: true
  87069. });
  87070. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  87071. /**
  87072. * Gets the animation properties override
  87073. */
  87074. get: function () {
  87075. return this._skeleton.animationPropertiesOverride;
  87076. },
  87077. enumerable: true,
  87078. configurable: true
  87079. });
  87080. // Methods
  87081. Bone.prototype._decompose = function () {
  87082. if (!this._needToDecompose) {
  87083. return;
  87084. }
  87085. this._needToDecompose = false;
  87086. if (!this._localScaling) {
  87087. this._localScaling = BABYLON.Vector3.Zero();
  87088. this._localRotation = BABYLON.Quaternion.Zero();
  87089. this._localPosition = BABYLON.Vector3.Zero();
  87090. }
  87091. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  87092. };
  87093. Bone.prototype._compose = function () {
  87094. if (!this._needToCompose) {
  87095. return;
  87096. }
  87097. this._needToCompose = false;
  87098. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  87099. };
  87100. /**
  87101. * Update the base and local matrices
  87102. * @param matrix defines the new base or local matrix
  87103. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  87104. * @param updateLocalMatrix defines if the local matrix should be updated
  87105. */
  87106. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  87107. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  87108. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  87109. this._baseMatrix.copyFrom(matrix);
  87110. if (updateDifferenceMatrix) {
  87111. this._updateDifferenceMatrix();
  87112. }
  87113. if (updateLocalMatrix) {
  87114. this._localMatrix.copyFrom(matrix);
  87115. this._markAsDirtyAndDecompose();
  87116. }
  87117. else {
  87118. this.markAsDirty();
  87119. }
  87120. };
  87121. /** @hidden */
  87122. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  87123. if (updateChildren === void 0) { updateChildren = true; }
  87124. if (!rootMatrix) {
  87125. rootMatrix = this._baseMatrix;
  87126. }
  87127. if (this._parent) {
  87128. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87129. }
  87130. else {
  87131. this._absoluteTransform.copyFrom(rootMatrix);
  87132. }
  87133. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  87134. if (updateChildren) {
  87135. for (var index = 0; index < this.children.length; index++) {
  87136. this.children[index]._updateDifferenceMatrix();
  87137. }
  87138. }
  87139. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  87140. };
  87141. /**
  87142. * Flag the bone as dirty (Forcing it to update everything)
  87143. */
  87144. Bone.prototype.markAsDirty = function () {
  87145. this._currentRenderId++;
  87146. this._childRenderId++;
  87147. this._skeleton._markAsDirty();
  87148. };
  87149. Bone.prototype._markAsDirtyAndCompose = function () {
  87150. this.markAsDirty();
  87151. this._needToCompose = true;
  87152. };
  87153. Bone.prototype._markAsDirtyAndDecompose = function () {
  87154. this.markAsDirty();
  87155. this._needToDecompose = true;
  87156. };
  87157. /**
  87158. * Copy an animation range from another bone
  87159. * @param source defines the source bone
  87160. * @param rangeName defines the range name to copy
  87161. * @param frameOffset defines the frame offset
  87162. * @param rescaleAsRequired defines if rescaling must be applied if required
  87163. * @param skelDimensionsRatio defines the scaling ratio
  87164. * @returns true if operation was successful
  87165. */
  87166. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  87167. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87168. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  87169. // all animation may be coming from a library skeleton, so may need to create animation
  87170. if (this.animations.length === 0) {
  87171. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  87172. this.animations[0].setKeys([]);
  87173. }
  87174. // get animation info / verify there is such a range from the source bone
  87175. var sourceRange = source.animations[0].getRange(rangeName);
  87176. if (!sourceRange) {
  87177. return false;
  87178. }
  87179. var from = sourceRange.from;
  87180. var to = sourceRange.to;
  87181. var sourceKeys = source.animations[0].getKeys();
  87182. // rescaling prep
  87183. var sourceBoneLength = source.length;
  87184. var sourceParent = source.getParent();
  87185. var parent = this.getParent();
  87186. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  87187. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  87188. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  87189. var destKeys = this.animations[0].getKeys();
  87190. // loop vars declaration
  87191. var orig;
  87192. var origTranslation;
  87193. var mat;
  87194. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  87195. orig = sourceKeys[key];
  87196. if (orig.frame >= from && orig.frame <= to) {
  87197. if (rescaleAsRequired) {
  87198. mat = orig.value.clone();
  87199. // scale based on parent ratio, when bone has parent
  87200. if (parentScalingReqd) {
  87201. origTranslation = mat.getTranslation();
  87202. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  87203. // scale based on skeleton dimension ratio when root bone, and value is passed
  87204. }
  87205. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  87206. origTranslation = mat.getTranslation();
  87207. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  87208. // use original when root bone, and no data for skelDimensionsRatio
  87209. }
  87210. else {
  87211. mat = orig.value;
  87212. }
  87213. }
  87214. else {
  87215. mat = orig.value;
  87216. }
  87217. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  87218. }
  87219. }
  87220. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  87221. return true;
  87222. };
  87223. /**
  87224. * Translate the bone in local or world space
  87225. * @param vec The amount to translate the bone
  87226. * @param space The space that the translation is in
  87227. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87228. */
  87229. Bone.prototype.translate = function (vec, space, mesh) {
  87230. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87231. var lm = this.getLocalMatrix();
  87232. if (space == BABYLON.Space.LOCAL) {
  87233. lm.m[12] += vec.x;
  87234. lm.m[13] += vec.y;
  87235. lm.m[14] += vec.z;
  87236. }
  87237. else {
  87238. var wm = null;
  87239. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87240. if (mesh) {
  87241. wm = mesh.getWorldMatrix();
  87242. }
  87243. this._skeleton.computeAbsoluteTransforms();
  87244. var tmat = Bone._tmpMats[0];
  87245. var tvec = Bone._tmpVecs[0];
  87246. if (this._parent) {
  87247. if (mesh && wm) {
  87248. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87249. tmat.multiplyToRef(wm, tmat);
  87250. }
  87251. else {
  87252. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87253. }
  87254. }
  87255. tmat.m[12] = 0;
  87256. tmat.m[13] = 0;
  87257. tmat.m[14] = 0;
  87258. tmat.invert();
  87259. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  87260. lm.m[12] += tvec.x;
  87261. lm.m[13] += tvec.y;
  87262. lm.m[14] += tvec.z;
  87263. }
  87264. this._markAsDirtyAndDecompose();
  87265. };
  87266. /**
  87267. * Set the postion of the bone in local or world space
  87268. * @param position The position to set the bone
  87269. * @param space The space that the position is in
  87270. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87271. */
  87272. Bone.prototype.setPosition = function (position, space, mesh) {
  87273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87274. var lm = this.getLocalMatrix();
  87275. if (space == BABYLON.Space.LOCAL) {
  87276. lm.m[12] = position.x;
  87277. lm.m[13] = position.y;
  87278. lm.m[14] = position.z;
  87279. }
  87280. else {
  87281. var wm = null;
  87282. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87283. if (mesh) {
  87284. wm = mesh.getWorldMatrix();
  87285. }
  87286. this._skeleton.computeAbsoluteTransforms();
  87287. var tmat = Bone._tmpMats[0];
  87288. var vec = Bone._tmpVecs[0];
  87289. if (this._parent) {
  87290. if (mesh && wm) {
  87291. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87292. tmat.multiplyToRef(wm, tmat);
  87293. }
  87294. else {
  87295. tmat.copyFrom(this._parent.getAbsoluteTransform());
  87296. }
  87297. }
  87298. tmat.invert();
  87299. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  87300. lm.m[12] = vec.x;
  87301. lm.m[13] = vec.y;
  87302. lm.m[14] = vec.z;
  87303. }
  87304. this._markAsDirtyAndDecompose();
  87305. };
  87306. /**
  87307. * Set the absolute position of the bone (world space)
  87308. * @param position The position to set the bone
  87309. * @param mesh The mesh that this bone is attached to
  87310. */
  87311. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  87312. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  87313. };
  87314. /**
  87315. * Scale the bone on the x, y and z axes (in local space)
  87316. * @param x The amount to scale the bone on the x axis
  87317. * @param y The amount to scale the bone on the y axis
  87318. * @param z The amount to scale the bone on the z axis
  87319. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  87320. */
  87321. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  87322. if (scaleChildren === void 0) { scaleChildren = false; }
  87323. var locMat = this.getLocalMatrix();
  87324. // Apply new scaling on top of current local matrix
  87325. var scaleMat = Bone._tmpMats[0];
  87326. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  87327. scaleMat.multiplyToRef(locMat, locMat);
  87328. // Invert scaling matrix and apply the inverse to all children
  87329. scaleMat.invert();
  87330. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  87331. var child = _a[_i];
  87332. var cm = child.getLocalMatrix();
  87333. cm.multiplyToRef(scaleMat, cm);
  87334. cm.m[12] *= x;
  87335. cm.m[13] *= y;
  87336. cm.m[14] *= z;
  87337. child._markAsDirtyAndDecompose();
  87338. }
  87339. this._markAsDirtyAndDecompose();
  87340. if (scaleChildren) {
  87341. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  87342. var child = _c[_b];
  87343. child.scale(x, y, z, scaleChildren);
  87344. }
  87345. }
  87346. };
  87347. /**
  87348. * Set the bone scaling in local space
  87349. * @param scale defines the scaling vector
  87350. */
  87351. Bone.prototype.setScale = function (scale) {
  87352. this._decompose();
  87353. this._localScaling.copyFrom(scale);
  87354. this._markAsDirtyAndCompose();
  87355. };
  87356. /**
  87357. * Gets the current scaling in local space
  87358. * @returns the current scaling vector
  87359. */
  87360. Bone.prototype.getScale = function () {
  87361. this._decompose();
  87362. return this._localScaling;
  87363. };
  87364. /**
  87365. * Gets the current scaling in local space and stores it in a target vector
  87366. * @param result defines the target vector
  87367. */
  87368. Bone.prototype.getScaleToRef = function (result) {
  87369. this._decompose();
  87370. result.copyFrom(this._localScaling);
  87371. };
  87372. /**
  87373. * Set the yaw, pitch, and roll of the bone in local or world space
  87374. * @param yaw The rotation of the bone on the y axis
  87375. * @param pitch The rotation of the bone on the x axis
  87376. * @param roll The rotation of the bone on the z axis
  87377. * @param space The space that the axes of rotation are in
  87378. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87379. */
  87380. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  87381. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87382. if (space === BABYLON.Space.LOCAL) {
  87383. var quat = Bone._tmpQuat;
  87384. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  87385. this.setRotationQuaternion(quat, space, mesh);
  87386. return;
  87387. }
  87388. var rotMatInv = Bone._tmpMats[0];
  87389. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87390. return;
  87391. }
  87392. var rotMat = Bone._tmpMats[1];
  87393. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  87394. rotMatInv.multiplyToRef(rotMat, rotMat);
  87395. this._rotateWithMatrix(rotMat, space, mesh);
  87396. };
  87397. /**
  87398. * Add a rotation to the bone on an axis in local or world space
  87399. * @param axis The axis to rotate the bone on
  87400. * @param amount The amount to rotate the bone
  87401. * @param space The space that the axis is in
  87402. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87403. */
  87404. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  87405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87406. var rmat = Bone._tmpMats[0];
  87407. rmat.m[12] = 0;
  87408. rmat.m[13] = 0;
  87409. rmat.m[14] = 0;
  87410. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  87411. this._rotateWithMatrix(rmat, space, mesh);
  87412. };
  87413. /**
  87414. * Set the rotation of the bone to a particular axis angle in local or world space
  87415. * @param axis The axis to rotate the bone on
  87416. * @param angle The angle that the bone should be rotated to
  87417. * @param space The space that the axis is in
  87418. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87419. */
  87420. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  87421. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87422. if (space === BABYLON.Space.LOCAL) {
  87423. var quat = Bone._tmpQuat;
  87424. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  87425. this.setRotationQuaternion(quat, space, mesh);
  87426. return;
  87427. }
  87428. var rotMatInv = Bone._tmpMats[0];
  87429. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87430. return;
  87431. }
  87432. var rotMat = Bone._tmpMats[1];
  87433. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  87434. rotMatInv.multiplyToRef(rotMat, rotMat);
  87435. this._rotateWithMatrix(rotMat, space, mesh);
  87436. };
  87437. /**
  87438. * Set the euler rotation of the bone in local of world space
  87439. * @param rotation The euler rotation that the bone should be set to
  87440. * @param space The space that the rotation is in
  87441. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87442. */
  87443. Bone.prototype.setRotation = function (rotation, space, mesh) {
  87444. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87445. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  87446. };
  87447. /**
  87448. * Set the quaternion rotation of the bone in local of world space
  87449. * @param quat The quaternion rotation that the bone should be set to
  87450. * @param space The space that the rotation is in
  87451. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87452. */
  87453. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  87454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87455. if (space === BABYLON.Space.LOCAL) {
  87456. this._decompose();
  87457. this._localRotation.copyFrom(quat);
  87458. this._markAsDirtyAndCompose();
  87459. return;
  87460. }
  87461. var rotMatInv = Bone._tmpMats[0];
  87462. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87463. return;
  87464. }
  87465. var rotMat = Bone._tmpMats[1];
  87466. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  87467. rotMatInv.multiplyToRef(rotMat, rotMat);
  87468. this._rotateWithMatrix(rotMat, space, mesh);
  87469. };
  87470. /**
  87471. * Set the rotation matrix of the bone in local of world space
  87472. * @param rotMat The rotation matrix that the bone should be set to
  87473. * @param space The space that the rotation is in
  87474. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87475. */
  87476. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  87477. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87478. if (space === BABYLON.Space.LOCAL) {
  87479. var quat = Bone._tmpQuat;
  87480. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  87481. this.setRotationQuaternion(quat, space, mesh);
  87482. return;
  87483. }
  87484. var rotMatInv = Bone._tmpMats[0];
  87485. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  87486. return;
  87487. }
  87488. var rotMat2 = Bone._tmpMats[1];
  87489. rotMat2.copyFrom(rotMat);
  87490. rotMatInv.multiplyToRef(rotMat, rotMat2);
  87491. this._rotateWithMatrix(rotMat2, space, mesh);
  87492. };
  87493. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  87494. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87495. var lmat = this.getLocalMatrix();
  87496. var lx = lmat.m[12];
  87497. var ly = lmat.m[13];
  87498. var lz = lmat.m[14];
  87499. var parent = this.getParent();
  87500. var parentScale = Bone._tmpMats[3];
  87501. var parentScaleInv = Bone._tmpMats[4];
  87502. if (parent && space == BABYLON.Space.WORLD) {
  87503. if (mesh) {
  87504. parentScale.copyFrom(mesh.getWorldMatrix());
  87505. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  87506. }
  87507. else {
  87508. parentScale.copyFrom(parent.getAbsoluteTransform());
  87509. }
  87510. parentScaleInv.copyFrom(parentScale);
  87511. parentScaleInv.invert();
  87512. lmat.multiplyToRef(parentScale, lmat);
  87513. lmat.multiplyToRef(rmat, lmat);
  87514. lmat.multiplyToRef(parentScaleInv, lmat);
  87515. }
  87516. else {
  87517. if (space == BABYLON.Space.WORLD && mesh) {
  87518. parentScale.copyFrom(mesh.getWorldMatrix());
  87519. parentScaleInv.copyFrom(parentScale);
  87520. parentScaleInv.invert();
  87521. lmat.multiplyToRef(parentScale, lmat);
  87522. lmat.multiplyToRef(rmat, lmat);
  87523. lmat.multiplyToRef(parentScaleInv, lmat);
  87524. }
  87525. else {
  87526. lmat.multiplyToRef(rmat, lmat);
  87527. }
  87528. }
  87529. lmat.m[12] = lx;
  87530. lmat.m[13] = ly;
  87531. lmat.m[14] = lz;
  87532. this.computeAbsoluteTransforms();
  87533. this._markAsDirtyAndDecompose();
  87534. };
  87535. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  87536. var scaleMatrix = Bone._tmpMats[2];
  87537. rotMatInv.copyFrom(this.getAbsoluteTransform());
  87538. if (mesh) {
  87539. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  87540. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  87541. }
  87542. rotMatInv.invert();
  87543. if (isNaN(rotMatInv.m[0])) {
  87544. // Matrix failed to invert.
  87545. // This can happen if scale is zero for example.
  87546. return false;
  87547. }
  87548. scaleMatrix.m[0] *= this._scalingDeterminant;
  87549. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  87550. return true;
  87551. };
  87552. /**
  87553. * Get the position of the bone in local or world space
  87554. * @param space The space that the returned position is in
  87555. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87556. * @returns The position of the bone
  87557. */
  87558. Bone.prototype.getPosition = function (space, mesh) {
  87559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87560. if (mesh === void 0) { mesh = null; }
  87561. var pos = BABYLON.Vector3.Zero();
  87562. this.getPositionToRef(space, mesh, pos);
  87563. return pos;
  87564. };
  87565. /**
  87566. * Copy the position of the bone to a vector3 in local or world space
  87567. * @param space The space that the returned position is in
  87568. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87569. * @param result The vector3 to copy the position to
  87570. */
  87571. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  87572. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87573. if (space == BABYLON.Space.LOCAL) {
  87574. var lm = this.getLocalMatrix();
  87575. result.x = lm.m[12];
  87576. result.y = lm.m[13];
  87577. result.z = lm.m[14];
  87578. }
  87579. else {
  87580. var wm = null;
  87581. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87582. if (mesh) {
  87583. wm = mesh.getWorldMatrix();
  87584. }
  87585. this._skeleton.computeAbsoluteTransforms();
  87586. var tmat = Bone._tmpMats[0];
  87587. if (mesh && wm) {
  87588. tmat.copyFrom(this.getAbsoluteTransform());
  87589. tmat.multiplyToRef(wm, tmat);
  87590. }
  87591. else {
  87592. tmat = this.getAbsoluteTransform();
  87593. }
  87594. result.x = tmat.m[12];
  87595. result.y = tmat.m[13];
  87596. result.z = tmat.m[14];
  87597. }
  87598. };
  87599. /**
  87600. * Get the absolute position of the bone (world space)
  87601. * @param mesh The mesh that this bone is attached to
  87602. * @returns The absolute position of the bone
  87603. */
  87604. Bone.prototype.getAbsolutePosition = function (mesh) {
  87605. if (mesh === void 0) { mesh = null; }
  87606. var pos = BABYLON.Vector3.Zero();
  87607. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  87608. return pos;
  87609. };
  87610. /**
  87611. * Copy the absolute position of the bone (world space) to the result param
  87612. * @param mesh The mesh that this bone is attached to
  87613. * @param result The vector3 to copy the absolute position to
  87614. */
  87615. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  87616. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  87617. };
  87618. /**
  87619. * Compute the absolute transforms of this bone and its children
  87620. */
  87621. Bone.prototype.computeAbsoluteTransforms = function () {
  87622. this._compose();
  87623. if (this._parent) {
  87624. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  87625. }
  87626. else {
  87627. this._absoluteTransform.copyFrom(this._localMatrix);
  87628. var poseMatrix = this._skeleton.getPoseMatrix();
  87629. if (poseMatrix) {
  87630. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  87631. }
  87632. }
  87633. var children = this.children;
  87634. var len = children.length;
  87635. for (var i = 0; i < len; i++) {
  87636. children[i].computeAbsoluteTransforms();
  87637. }
  87638. };
  87639. /**
  87640. * Get the world direction from an axis that is in the local space of the bone
  87641. * @param localAxis The local direction that is used to compute the world direction
  87642. * @param mesh The mesh that this bone is attached to
  87643. * @returns The world direction
  87644. */
  87645. Bone.prototype.getDirection = function (localAxis, mesh) {
  87646. if (mesh === void 0) { mesh = null; }
  87647. var result = BABYLON.Vector3.Zero();
  87648. this.getDirectionToRef(localAxis, mesh, result);
  87649. return result;
  87650. };
  87651. /**
  87652. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  87653. * @param localAxis The local direction that is used to compute the world direction
  87654. * @param mesh The mesh that this bone is attached to
  87655. * @param result The vector3 that the world direction will be copied to
  87656. */
  87657. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  87658. if (mesh === void 0) { mesh = null; }
  87659. var wm = null;
  87660. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87661. if (mesh) {
  87662. wm = mesh.getWorldMatrix();
  87663. }
  87664. this._skeleton.computeAbsoluteTransforms();
  87665. var mat = Bone._tmpMats[0];
  87666. mat.copyFrom(this.getAbsoluteTransform());
  87667. if (mesh && wm) {
  87668. mat.multiplyToRef(wm, mat);
  87669. }
  87670. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  87671. result.normalize();
  87672. };
  87673. /**
  87674. * Get the euler rotation of the bone in local or world space
  87675. * @param space The space that the rotation should be in
  87676. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87677. * @returns The euler rotation
  87678. */
  87679. Bone.prototype.getRotation = function (space, mesh) {
  87680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87681. if (mesh === void 0) { mesh = null; }
  87682. var result = BABYLON.Vector3.Zero();
  87683. this.getRotationToRef(space, mesh, result);
  87684. return result;
  87685. };
  87686. /**
  87687. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  87688. * @param space The space that the rotation should be in
  87689. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87690. * @param result The vector3 that the rotation should be copied to
  87691. */
  87692. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  87693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87694. if (mesh === void 0) { mesh = null; }
  87695. var quat = Bone._tmpQuat;
  87696. this.getRotationQuaternionToRef(space, mesh, quat);
  87697. quat.toEulerAnglesToRef(result);
  87698. };
  87699. /**
  87700. * Get the quaternion rotation of the bone in either local or world space
  87701. * @param space The space that the rotation should be in
  87702. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87703. * @returns The quaternion rotation
  87704. */
  87705. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  87706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87707. if (mesh === void 0) { mesh = null; }
  87708. var result = BABYLON.Quaternion.Identity();
  87709. this.getRotationQuaternionToRef(space, mesh, result);
  87710. return result;
  87711. };
  87712. /**
  87713. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  87714. * @param space The space that the rotation should be in
  87715. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87716. * @param result The quaternion that the rotation should be copied to
  87717. */
  87718. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  87719. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87720. if (mesh === void 0) { mesh = null; }
  87721. if (space == BABYLON.Space.LOCAL) {
  87722. this._decompose();
  87723. result.copyFrom(this._localRotation);
  87724. }
  87725. else {
  87726. var mat = Bone._tmpMats[0];
  87727. var amat = this.getAbsoluteTransform();
  87728. if (mesh) {
  87729. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87730. }
  87731. else {
  87732. mat.copyFrom(amat);
  87733. }
  87734. mat.m[0] *= this._scalingDeterminant;
  87735. mat.m[1] *= this._scalingDeterminant;
  87736. mat.m[2] *= this._scalingDeterminant;
  87737. mat.decompose(undefined, result, undefined);
  87738. }
  87739. };
  87740. /**
  87741. * Get the rotation matrix of the bone in local or world space
  87742. * @param space The space that the rotation should be in
  87743. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87744. * @returns The rotation matrix
  87745. */
  87746. Bone.prototype.getRotationMatrix = function (space, mesh) {
  87747. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87748. var result = BABYLON.Matrix.Identity();
  87749. this.getRotationMatrixToRef(space, mesh, result);
  87750. return result;
  87751. };
  87752. /**
  87753. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  87754. * @param space The space that the rotation should be in
  87755. * @param mesh The mesh that this bone is attached to. This is only used in world space
  87756. * @param result The quaternion that the rotation should be copied to
  87757. */
  87758. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  87759. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  87760. if (space == BABYLON.Space.LOCAL) {
  87761. this.getLocalMatrix().getRotationMatrixToRef(result);
  87762. }
  87763. else {
  87764. var mat = Bone._tmpMats[0];
  87765. var amat = this.getAbsoluteTransform();
  87766. if (mesh) {
  87767. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  87768. }
  87769. else {
  87770. mat.copyFrom(amat);
  87771. }
  87772. mat.m[0] *= this._scalingDeterminant;
  87773. mat.m[1] *= this._scalingDeterminant;
  87774. mat.m[2] *= this._scalingDeterminant;
  87775. mat.getRotationMatrixToRef(result);
  87776. }
  87777. };
  87778. /**
  87779. * Get the world position of a point that is in the local space of the bone
  87780. * @param position The local position
  87781. * @param mesh The mesh that this bone is attached to
  87782. * @returns The world position
  87783. */
  87784. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  87785. if (mesh === void 0) { mesh = null; }
  87786. var result = BABYLON.Vector3.Zero();
  87787. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  87788. return result;
  87789. };
  87790. /**
  87791. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  87792. * @param position The local position
  87793. * @param mesh The mesh that this bone is attached to
  87794. * @param result The vector3 that the world position should be copied to
  87795. */
  87796. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  87797. if (mesh === void 0) { mesh = null; }
  87798. var wm = null;
  87799. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87800. if (mesh) {
  87801. wm = mesh.getWorldMatrix();
  87802. }
  87803. this._skeleton.computeAbsoluteTransforms();
  87804. var tmat = Bone._tmpMats[0];
  87805. if (mesh && wm) {
  87806. tmat.copyFrom(this.getAbsoluteTransform());
  87807. tmat.multiplyToRef(wm, tmat);
  87808. }
  87809. else {
  87810. tmat = this.getAbsoluteTransform();
  87811. }
  87812. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87813. };
  87814. /**
  87815. * Get the local position of a point that is in world space
  87816. * @param position The world position
  87817. * @param mesh The mesh that this bone is attached to
  87818. * @returns The local position
  87819. */
  87820. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  87821. if (mesh === void 0) { mesh = null; }
  87822. var result = BABYLON.Vector3.Zero();
  87823. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  87824. return result;
  87825. };
  87826. /**
  87827. * Get the local position of a point that is in world space and copy it to the result param
  87828. * @param position The world position
  87829. * @param mesh The mesh that this bone is attached to
  87830. * @param result The vector3 that the local position should be copied to
  87831. */
  87832. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  87833. if (mesh === void 0) { mesh = null; }
  87834. var wm = null;
  87835. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  87836. if (mesh) {
  87837. wm = mesh.getWorldMatrix();
  87838. }
  87839. this._skeleton.computeAbsoluteTransforms();
  87840. var tmat = Bone._tmpMats[0];
  87841. tmat.copyFrom(this.getAbsoluteTransform());
  87842. if (mesh && wm) {
  87843. tmat.multiplyToRef(wm, tmat);
  87844. }
  87845. tmat.invert();
  87846. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  87847. };
  87848. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87849. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  87850. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87851. return Bone;
  87852. }(BABYLON.Node));
  87853. BABYLON.Bone = Bone;
  87854. })(BABYLON || (BABYLON = {}));
  87855. //# sourceMappingURL=babylon.bone.js.map
  87856. var BABYLON;
  87857. (function (BABYLON) {
  87858. /**
  87859. * Class used to apply inverse kinematics to bones
  87860. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  87861. */
  87862. var BoneIKController = /** @class */ (function () {
  87863. /**
  87864. * Creates a new BoneIKController
  87865. * @param mesh defines the mesh to control
  87866. * @param bone defines the bone to control
  87867. * @param options defines options to set up the controller
  87868. */
  87869. function BoneIKController(mesh, bone, options) {
  87870. /**
  87871. * Gets or sets the target position
  87872. */
  87873. this.targetPosition = BABYLON.Vector3.Zero();
  87874. /**
  87875. * Gets or sets the pole target position
  87876. */
  87877. this.poleTargetPosition = BABYLON.Vector3.Zero();
  87878. /**
  87879. * Gets or sets the pole target local offset
  87880. */
  87881. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  87882. /**
  87883. * Gets or sets the pole angle
  87884. */
  87885. this.poleAngle = 0;
  87886. /**
  87887. * 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)
  87888. */
  87889. this.slerpAmount = 1;
  87890. this._bone1Quat = BABYLON.Quaternion.Identity();
  87891. this._bone1Mat = BABYLON.Matrix.Identity();
  87892. this._bone2Ang = Math.PI;
  87893. this._maxAngle = Math.PI;
  87894. this._rightHandedSystem = false;
  87895. this._bendAxis = BABYLON.Vector3.Right();
  87896. this._slerping = false;
  87897. this._adjustRoll = 0;
  87898. this._bone2 = bone;
  87899. this._bone1 = bone.getParent();
  87900. if (!this._bone1) {
  87901. return;
  87902. }
  87903. this.mesh = mesh;
  87904. var bonePos = bone.getPosition();
  87905. if (bone.getAbsoluteTransform().determinant() > 0) {
  87906. this._rightHandedSystem = true;
  87907. this._bendAxis.x = 0;
  87908. this._bendAxis.y = 0;
  87909. this._bendAxis.z = -1;
  87910. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  87911. this._adjustRoll = Math.PI * .5;
  87912. this._bendAxis.z = 1;
  87913. }
  87914. }
  87915. if (this._bone1.length) {
  87916. var boneScale1 = this._bone1.getScale();
  87917. var boneScale2 = this._bone2.getScale();
  87918. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  87919. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  87920. }
  87921. else if (this._bone1.children[0]) {
  87922. mesh.computeWorldMatrix(true);
  87923. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  87924. var pos2 = this._bone2.getAbsolutePosition(mesh);
  87925. var pos3 = this._bone1.getAbsolutePosition(mesh);
  87926. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  87927. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  87928. }
  87929. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  87930. this.maxAngle = Math.PI;
  87931. if (options) {
  87932. if (options.targetMesh) {
  87933. this.targetMesh = options.targetMesh;
  87934. this.targetMesh.computeWorldMatrix(true);
  87935. }
  87936. if (options.poleTargetMesh) {
  87937. this.poleTargetMesh = options.poleTargetMesh;
  87938. this.poleTargetMesh.computeWorldMatrix(true);
  87939. }
  87940. else if (options.poleTargetBone) {
  87941. this.poleTargetBone = options.poleTargetBone;
  87942. }
  87943. else if (this._bone1.getParent()) {
  87944. this.poleTargetBone = this._bone1.getParent();
  87945. }
  87946. if (options.poleTargetLocalOffset) {
  87947. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87948. }
  87949. if (options.poleAngle) {
  87950. this.poleAngle = options.poleAngle;
  87951. }
  87952. if (options.bendAxis) {
  87953. this._bendAxis.copyFrom(options.bendAxis);
  87954. }
  87955. if (options.maxAngle) {
  87956. this.maxAngle = options.maxAngle;
  87957. }
  87958. if (options.slerpAmount) {
  87959. this.slerpAmount = options.slerpAmount;
  87960. }
  87961. }
  87962. }
  87963. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87964. /**
  87965. * Gets or sets maximum allowed angle
  87966. */
  87967. get: function () {
  87968. return this._maxAngle;
  87969. },
  87970. set: function (value) {
  87971. this._setMaxAngle(value);
  87972. },
  87973. enumerable: true,
  87974. configurable: true
  87975. });
  87976. BoneIKController.prototype._setMaxAngle = function (ang) {
  87977. if (ang < 0) {
  87978. ang = 0;
  87979. }
  87980. if (ang > Math.PI || ang == undefined) {
  87981. ang = Math.PI;
  87982. }
  87983. this._maxAngle = ang;
  87984. var a = this._bone1Length;
  87985. var b = this._bone2Length;
  87986. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87987. };
  87988. /**
  87989. * Force the controller to update the bones
  87990. */
  87991. BoneIKController.prototype.update = function () {
  87992. var bone1 = this._bone1;
  87993. if (!bone1) {
  87994. return;
  87995. }
  87996. var target = this.targetPosition;
  87997. var poleTarget = this.poleTargetPosition;
  87998. var mat1 = BoneIKController._tmpMats[0];
  87999. var mat2 = BoneIKController._tmpMats[1];
  88000. if (this.targetMesh) {
  88001. target.copyFrom(this.targetMesh.getAbsolutePosition());
  88002. }
  88003. if (this.poleTargetBone) {
  88004. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  88005. }
  88006. else if (this.poleTargetMesh) {
  88007. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  88008. }
  88009. var bonePos = BoneIKController._tmpVecs[0];
  88010. var zaxis = BoneIKController._tmpVecs[1];
  88011. var xaxis = BoneIKController._tmpVecs[2];
  88012. var yaxis = BoneIKController._tmpVecs[3];
  88013. var upAxis = BoneIKController._tmpVecs[4];
  88014. var _tmpQuat = BoneIKController._tmpQuat;
  88015. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  88016. poleTarget.subtractToRef(bonePos, upAxis);
  88017. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  88018. upAxis.y = 1;
  88019. }
  88020. else {
  88021. upAxis.normalize();
  88022. }
  88023. target.subtractToRef(bonePos, yaxis);
  88024. yaxis.normalize();
  88025. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  88026. zaxis.normalize();
  88027. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  88028. xaxis.normalize();
  88029. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  88030. var a = this._bone1Length;
  88031. var b = this._bone2Length;
  88032. var c = BABYLON.Vector3.Distance(bonePos, target);
  88033. if (this._maxReach > 0) {
  88034. c = Math.min(this._maxReach, c);
  88035. }
  88036. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  88037. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  88038. if (acosa > 1) {
  88039. acosa = 1;
  88040. }
  88041. if (acosb > 1) {
  88042. acosb = 1;
  88043. }
  88044. if (acosa < -1) {
  88045. acosa = -1;
  88046. }
  88047. if (acosb < -1) {
  88048. acosb = -1;
  88049. }
  88050. var angA = Math.acos(acosa);
  88051. var angB = Math.acos(acosb);
  88052. var angC = -angA - angB;
  88053. if (this._rightHandedSystem) {
  88054. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  88055. mat2.multiplyToRef(mat1, mat1);
  88056. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  88057. mat2.multiplyToRef(mat1, mat1);
  88058. }
  88059. else {
  88060. var _tmpVec = BoneIKController._tmpVecs[5];
  88061. _tmpVec.copyFrom(this._bendAxis);
  88062. _tmpVec.x *= -1;
  88063. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  88064. mat2.multiplyToRef(mat1, mat1);
  88065. }
  88066. if (this.poleAngle) {
  88067. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  88068. mat1.multiplyToRef(mat2, mat1);
  88069. }
  88070. if (this._bone1) {
  88071. if (this.slerpAmount < 1) {
  88072. if (!this._slerping) {
  88073. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  88074. }
  88075. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  88076. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  88077. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  88078. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  88079. this._slerping = true;
  88080. }
  88081. else {
  88082. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  88083. this._bone1Mat.copyFrom(mat1);
  88084. this._slerping = false;
  88085. }
  88086. }
  88087. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  88088. this._bone2Ang = angC;
  88089. };
  88090. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88091. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  88092. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88093. return BoneIKController;
  88094. }());
  88095. BABYLON.BoneIKController = BoneIKController;
  88096. })(BABYLON || (BABYLON = {}));
  88097. //# sourceMappingURL=babylon.boneIKController.js.map
  88098. var BABYLON;
  88099. (function (BABYLON) {
  88100. /**
  88101. * Class used to make a bone look toward a point in space
  88102. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  88103. */
  88104. var BoneLookController = /** @class */ (function () {
  88105. /**
  88106. * Create a BoneLookController
  88107. * @param mesh the mesh that the bone belongs to
  88108. * @param bone the bone that will be looking to the target
  88109. * @param target the target Vector3 to look at
  88110. * @param settings optional settings:
  88111. * * maxYaw: the maximum angle the bone will yaw to
  88112. * * minYaw: the minimum angle the bone will yaw to
  88113. * * maxPitch: the maximum angle the bone will pitch to
  88114. * * minPitch: the minimum angle the bone will yaw to
  88115. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  88116. * * upAxis: the up axis of the coordinate system
  88117. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  88118. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  88119. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  88120. * * adjustYaw: used to make an adjustment to the yaw of the bone
  88121. * * adjustPitch: used to make an adjustment to the pitch of the bone
  88122. * * adjustRoll: used to make an adjustment to the roll of the bone
  88123. **/
  88124. function BoneLookController(mesh, bone, target, options) {
  88125. /**
  88126. * The up axis of the coordinate system that is used when the bone is rotated
  88127. */
  88128. this.upAxis = BABYLON.Vector3.Up();
  88129. /**
  88130. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  88131. */
  88132. this.upAxisSpace = BABYLON.Space.LOCAL;
  88133. /**
  88134. * Used to make an adjustment to the yaw of the bone
  88135. */
  88136. this.adjustYaw = 0;
  88137. /**
  88138. * Used to make an adjustment to the pitch of the bone
  88139. */
  88140. this.adjustPitch = 0;
  88141. /**
  88142. * Used to make an adjustment to the roll of the bone
  88143. */
  88144. this.adjustRoll = 0;
  88145. /**
  88146. * 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)
  88147. */
  88148. this.slerpAmount = 1;
  88149. this._boneQuat = BABYLON.Quaternion.Identity();
  88150. this._slerping = false;
  88151. this._firstFrameSkipped = false;
  88152. this._fowardAxis = BABYLON.Vector3.Forward();
  88153. this.mesh = mesh;
  88154. this.bone = bone;
  88155. this.target = target;
  88156. if (options) {
  88157. if (options.adjustYaw) {
  88158. this.adjustYaw = options.adjustYaw;
  88159. }
  88160. if (options.adjustPitch) {
  88161. this.adjustPitch = options.adjustPitch;
  88162. }
  88163. if (options.adjustRoll) {
  88164. this.adjustRoll = options.adjustRoll;
  88165. }
  88166. if (options.maxYaw != null) {
  88167. this.maxYaw = options.maxYaw;
  88168. }
  88169. else {
  88170. this.maxYaw = Math.PI;
  88171. }
  88172. if (options.minYaw != null) {
  88173. this.minYaw = options.minYaw;
  88174. }
  88175. else {
  88176. this.minYaw = -Math.PI;
  88177. }
  88178. if (options.maxPitch != null) {
  88179. this.maxPitch = options.maxPitch;
  88180. }
  88181. else {
  88182. this.maxPitch = Math.PI;
  88183. }
  88184. if (options.minPitch != null) {
  88185. this.minPitch = options.minPitch;
  88186. }
  88187. else {
  88188. this.minPitch = -Math.PI;
  88189. }
  88190. if (options.slerpAmount != null) {
  88191. this.slerpAmount = options.slerpAmount;
  88192. }
  88193. if (options.upAxis != null) {
  88194. this.upAxis = options.upAxis;
  88195. }
  88196. if (options.upAxisSpace != null) {
  88197. this.upAxisSpace = options.upAxisSpace;
  88198. }
  88199. if (options.yawAxis != null || options.pitchAxis != null) {
  88200. var newYawAxis = BABYLON.Axis.Y;
  88201. var newPitchAxis = BABYLON.Axis.X;
  88202. if (options.yawAxis != null) {
  88203. newYawAxis = options.yawAxis.clone();
  88204. newYawAxis.normalize();
  88205. }
  88206. if (options.pitchAxis != null) {
  88207. newPitchAxis = options.pitchAxis.clone();
  88208. newPitchAxis.normalize();
  88209. }
  88210. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  88211. this._transformYawPitch = BABYLON.Matrix.Identity();
  88212. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  88213. this._transformYawPitchInv = this._transformYawPitch.clone();
  88214. this._transformYawPitch.invert();
  88215. }
  88216. }
  88217. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  88218. this.upAxisSpace = BABYLON.Space.LOCAL;
  88219. }
  88220. }
  88221. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  88222. /**
  88223. * Gets or sets the minimum yaw angle that the bone can look to
  88224. */
  88225. get: function () {
  88226. return this._minYaw;
  88227. },
  88228. set: function (value) {
  88229. this._minYaw = value;
  88230. this._minYawSin = Math.sin(value);
  88231. this._minYawCos = Math.cos(value);
  88232. if (this._maxYaw != null) {
  88233. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88234. this._yawRange = this._maxYaw - this._minYaw;
  88235. }
  88236. },
  88237. enumerable: true,
  88238. configurable: true
  88239. });
  88240. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  88241. /**
  88242. * Gets or sets the maximum yaw angle that the bone can look to
  88243. */
  88244. get: function () {
  88245. return this._maxYaw;
  88246. },
  88247. set: function (value) {
  88248. this._maxYaw = value;
  88249. this._maxYawSin = Math.sin(value);
  88250. this._maxYawCos = Math.cos(value);
  88251. if (this._minYaw != null) {
  88252. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  88253. this._yawRange = this._maxYaw - this._minYaw;
  88254. }
  88255. },
  88256. enumerable: true,
  88257. configurable: true
  88258. });
  88259. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  88260. /**
  88261. * Gets or sets the minimum pitch angle that the bone can look to
  88262. */
  88263. get: function () {
  88264. return this._minPitch;
  88265. },
  88266. set: function (value) {
  88267. this._minPitch = value;
  88268. this._minPitchTan = Math.tan(value);
  88269. },
  88270. enumerable: true,
  88271. configurable: true
  88272. });
  88273. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  88274. /**
  88275. * Gets or sets the maximum pitch angle that the bone can look to
  88276. */
  88277. get: function () {
  88278. return this._maxPitch;
  88279. },
  88280. set: function (value) {
  88281. this._maxPitch = value;
  88282. this._maxPitchTan = Math.tan(value);
  88283. },
  88284. enumerable: true,
  88285. configurable: true
  88286. });
  88287. /**
  88288. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  88289. */
  88290. BoneLookController.prototype.update = function () {
  88291. //skip the first frame when slerping so that the mesh rotation is correct
  88292. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  88293. this._firstFrameSkipped = true;
  88294. return;
  88295. }
  88296. var bone = this.bone;
  88297. var bonePos = BoneLookController._tmpVecs[0];
  88298. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  88299. var target = this.target;
  88300. var _tmpMat1 = BoneLookController._tmpMats[0];
  88301. var _tmpMat2 = BoneLookController._tmpMats[1];
  88302. var mesh = this.mesh;
  88303. var parentBone = bone.getParent();
  88304. var upAxis = BoneLookController._tmpVecs[1];
  88305. upAxis.copyFrom(this.upAxis);
  88306. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  88307. if (this._transformYawPitch) {
  88308. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  88309. }
  88310. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  88311. }
  88312. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  88313. mesh.getDirectionToRef(upAxis, upAxis);
  88314. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  88315. upAxis.normalize();
  88316. }
  88317. }
  88318. var checkYaw = false;
  88319. var checkPitch = false;
  88320. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  88321. checkYaw = true;
  88322. }
  88323. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  88324. checkPitch = true;
  88325. }
  88326. if (checkYaw || checkPitch) {
  88327. var spaceMat = BoneLookController._tmpMats[2];
  88328. var spaceMatInv = BoneLookController._tmpMats[3];
  88329. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  88330. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  88331. }
  88332. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  88333. spaceMat.copyFrom(mesh.getWorldMatrix());
  88334. }
  88335. else {
  88336. var forwardAxis = BoneLookController._tmpVecs[2];
  88337. forwardAxis.copyFrom(this._fowardAxis);
  88338. if (this._transformYawPitch) {
  88339. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  88340. }
  88341. if (parentBone) {
  88342. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  88343. }
  88344. else {
  88345. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  88346. }
  88347. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  88348. rightAxis.normalize();
  88349. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  88350. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  88351. }
  88352. spaceMat.invertToRef(spaceMatInv);
  88353. var xzlen = null;
  88354. if (checkPitch) {
  88355. var localTarget = BoneLookController._tmpVecs[3];
  88356. target.subtractToRef(bonePos, localTarget);
  88357. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88358. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88359. var pitch = Math.atan2(localTarget.y, xzlen);
  88360. var newPitch = pitch;
  88361. if (pitch > this._maxPitch) {
  88362. localTarget.y = this._maxPitchTan * xzlen;
  88363. newPitch = this._maxPitch;
  88364. }
  88365. else if (pitch < this._minPitch) {
  88366. localTarget.y = this._minPitchTan * xzlen;
  88367. newPitch = this._minPitch;
  88368. }
  88369. if (pitch != newPitch) {
  88370. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88371. localTarget.addInPlace(bonePos);
  88372. target = localTarget;
  88373. }
  88374. }
  88375. if (checkYaw) {
  88376. var localTarget = BoneLookController._tmpVecs[4];
  88377. target.subtractToRef(bonePos, localTarget);
  88378. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  88379. var yaw = Math.atan2(localTarget.x, localTarget.z);
  88380. var newYaw = yaw;
  88381. if (yaw > this._maxYaw || yaw < this._minYaw) {
  88382. if (xzlen == null) {
  88383. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88384. }
  88385. if (this._yawRange > Math.PI) {
  88386. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  88387. localTarget.z = this._maxYawCos * xzlen;
  88388. localTarget.x = this._maxYawSin * xzlen;
  88389. newYaw = this._maxYaw;
  88390. }
  88391. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  88392. localTarget.z = this._minYawCos * xzlen;
  88393. localTarget.x = this._minYawSin * xzlen;
  88394. newYaw = this._minYaw;
  88395. }
  88396. }
  88397. else {
  88398. if (yaw > this._maxYaw) {
  88399. localTarget.z = this._maxYawCos * xzlen;
  88400. localTarget.x = this._maxYawSin * xzlen;
  88401. newYaw = this._maxYaw;
  88402. }
  88403. else if (yaw < this._minYaw) {
  88404. localTarget.z = this._minYawCos * xzlen;
  88405. localTarget.x = this._minYawSin * xzlen;
  88406. newYaw = this._minYaw;
  88407. }
  88408. }
  88409. }
  88410. if (this._slerping && this._yawRange > Math.PI) {
  88411. //are we going to be crossing into the min/max region?
  88412. var boneFwd = BoneLookController._tmpVecs[8];
  88413. boneFwd.copyFrom(BABYLON.Axis.Z);
  88414. if (this._transformYawPitch) {
  88415. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  88416. }
  88417. var boneRotMat = BoneLookController._tmpMats[4];
  88418. this._boneQuat.toRotationMatrix(boneRotMat);
  88419. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  88420. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  88421. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  88422. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  88423. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  88424. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  88425. if (angBtwTar > angBtwMidYaw) {
  88426. if (xzlen == null) {
  88427. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  88428. }
  88429. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  88430. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  88431. if (angBtwMin < angBtwMax) {
  88432. newYaw = boneYaw + Math.PI * .75;
  88433. localTarget.z = Math.cos(newYaw) * xzlen;
  88434. localTarget.x = Math.sin(newYaw) * xzlen;
  88435. }
  88436. else {
  88437. newYaw = boneYaw - Math.PI * .75;
  88438. localTarget.z = Math.cos(newYaw) * xzlen;
  88439. localTarget.x = Math.sin(newYaw) * xzlen;
  88440. }
  88441. }
  88442. }
  88443. if (yaw != newYaw) {
  88444. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  88445. localTarget.addInPlace(bonePos);
  88446. target = localTarget;
  88447. }
  88448. }
  88449. }
  88450. var zaxis = BoneLookController._tmpVecs[5];
  88451. var xaxis = BoneLookController._tmpVecs[6];
  88452. var yaxis = BoneLookController._tmpVecs[7];
  88453. var _tmpQuat = BoneLookController._tmpQuat;
  88454. target.subtractToRef(bonePos, zaxis);
  88455. zaxis.normalize();
  88456. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  88457. xaxis.normalize();
  88458. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  88459. yaxis.normalize();
  88460. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  88461. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  88462. return;
  88463. }
  88464. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  88465. return;
  88466. }
  88467. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  88468. return;
  88469. }
  88470. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  88471. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  88472. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  88473. }
  88474. if (this.slerpAmount < 1) {
  88475. if (!this._slerping) {
  88476. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  88477. }
  88478. if (this._transformYawPitch) {
  88479. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88480. }
  88481. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  88482. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  88483. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  88484. this._slerping = true;
  88485. }
  88486. else {
  88487. if (this._transformYawPitch) {
  88488. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  88489. }
  88490. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  88491. this._slerping = false;
  88492. }
  88493. };
  88494. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  88495. var angDiff = ang2 - ang1;
  88496. angDiff %= Math.PI * 2;
  88497. if (angDiff > Math.PI) {
  88498. angDiff -= Math.PI * 2;
  88499. }
  88500. else if (angDiff < -Math.PI) {
  88501. angDiff += Math.PI * 2;
  88502. }
  88503. return angDiff;
  88504. };
  88505. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  88506. ang1 %= (2 * Math.PI);
  88507. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88508. ang2 %= (2 * Math.PI);
  88509. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88510. var ab = 0;
  88511. if (ang1 < ang2) {
  88512. ab = ang2 - ang1;
  88513. }
  88514. else {
  88515. ab = ang1 - ang2;
  88516. }
  88517. if (ab > Math.PI) {
  88518. ab = Math.PI * 2 - ab;
  88519. }
  88520. return ab;
  88521. };
  88522. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  88523. ang %= (2 * Math.PI);
  88524. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  88525. ang1 %= (2 * Math.PI);
  88526. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  88527. ang2 %= (2 * Math.PI);
  88528. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  88529. if (ang1 < ang2) {
  88530. if (ang > ang1 && ang < ang2) {
  88531. return true;
  88532. }
  88533. }
  88534. else {
  88535. if (ang > ang2 && ang < ang1) {
  88536. return true;
  88537. }
  88538. }
  88539. return false;
  88540. };
  88541. 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()];
  88542. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  88543. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  88544. return BoneLookController;
  88545. }());
  88546. BABYLON.BoneLookController = BoneLookController;
  88547. })(BABYLON || (BABYLON = {}));
  88548. //# sourceMappingURL=babylon.boneLookController.js.map
  88549. var BABYLON;
  88550. (function (BABYLON) {
  88551. /**
  88552. * Class used to handle skinning animations
  88553. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88554. */
  88555. var Skeleton = /** @class */ (function () {
  88556. /**
  88557. * Creates a new skeleton
  88558. * @param name defines the skeleton name
  88559. * @param id defines the skeleton Id
  88560. * @param scene defines the hosting scene
  88561. */
  88562. function Skeleton(
  88563. /** defines the skeleton name */
  88564. name,
  88565. /** defines the skeleton Id */
  88566. id, scene) {
  88567. this.name = name;
  88568. this.id = id;
  88569. /**
  88570. * Gets the list of child bones
  88571. */
  88572. this.bones = new Array();
  88573. /**
  88574. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  88575. */
  88576. this.needInitialSkinMatrix = false;
  88577. this._isDirty = true;
  88578. this._meshesWithPoseMatrix = new Array();
  88579. this._identity = BABYLON.Matrix.Identity();
  88580. this._ranges = {};
  88581. this._lastAbsoluteTransformsUpdateId = -1;
  88582. /**
  88583. * Specifies if the skeleton should be serialized
  88584. */
  88585. this.doNotSerialize = false;
  88586. this._animationPropertiesOverride = null;
  88587. // Events
  88588. /**
  88589. * An observable triggered before computing the skeleton's matrices
  88590. */
  88591. this.onBeforeComputeObservable = new BABYLON.Observable();
  88592. this.bones = [];
  88593. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88594. scene.skeletons.push(this);
  88595. //make sure it will recalculate the matrix next time prepare is called.
  88596. this._isDirty = true;
  88597. }
  88598. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  88599. /**
  88600. * Gets or sets the animation properties override
  88601. */
  88602. get: function () {
  88603. if (!this._animationPropertiesOverride) {
  88604. return this._scene.animationPropertiesOverride;
  88605. }
  88606. return this._animationPropertiesOverride;
  88607. },
  88608. set: function (value) {
  88609. this._animationPropertiesOverride = value;
  88610. },
  88611. enumerable: true,
  88612. configurable: true
  88613. });
  88614. // Members
  88615. /**
  88616. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  88617. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  88618. * @returns a Float32Array containing matrices data
  88619. */
  88620. Skeleton.prototype.getTransformMatrices = function (mesh) {
  88621. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  88622. return mesh._bonesTransformMatrices;
  88623. }
  88624. if (!this._transformMatrices) {
  88625. this.prepare();
  88626. }
  88627. return this._transformMatrices;
  88628. };
  88629. /**
  88630. * Gets the current hosting scene
  88631. * @returns a scene object
  88632. */
  88633. Skeleton.prototype.getScene = function () {
  88634. return this._scene;
  88635. };
  88636. // Methods
  88637. /**
  88638. * Gets a string representing the current skeleton data
  88639. * @param fullDetails defines a boolean indicating if we want a verbose version
  88640. * @returns a string representing the current skeleton data
  88641. */
  88642. Skeleton.prototype.toString = function (fullDetails) {
  88643. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  88644. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  88645. if (fullDetails) {
  88646. ret += ", Ranges: {";
  88647. var first = true;
  88648. for (var name_1 in this._ranges) {
  88649. if (first) {
  88650. ret += ", ";
  88651. first = false;
  88652. }
  88653. ret += name_1;
  88654. }
  88655. ret += "}";
  88656. }
  88657. return ret;
  88658. };
  88659. /**
  88660. * Get bone's index searching by name
  88661. * @param name defines bone's name to search for
  88662. * @return the indice of the bone. Returns -1 if not found
  88663. */
  88664. Skeleton.prototype.getBoneIndexByName = function (name) {
  88665. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  88666. if (this.bones[boneIndex].name === name) {
  88667. return boneIndex;
  88668. }
  88669. }
  88670. return -1;
  88671. };
  88672. /**
  88673. * Creater a new animation range
  88674. * @param name defines the name of the range
  88675. * @param from defines the start key
  88676. * @param to defines the end key
  88677. */
  88678. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  88679. // check name not already in use
  88680. if (!this._ranges[name]) {
  88681. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  88682. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88683. if (this.bones[i].animations[0]) {
  88684. this.bones[i].animations[0].createRange(name, from, to);
  88685. }
  88686. }
  88687. }
  88688. };
  88689. /**
  88690. * Delete a specific animation range
  88691. * @param name defines the name of the range
  88692. * @param deleteFrames defines if frames must be removed as well
  88693. */
  88694. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  88695. if (deleteFrames === void 0) { deleteFrames = true; }
  88696. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88697. if (this.bones[i].animations[0]) {
  88698. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  88699. }
  88700. }
  88701. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  88702. };
  88703. /**
  88704. * Gets a specific animation range
  88705. * @param name defines the name of the range to look for
  88706. * @returns the requested animation range or null if not found
  88707. */
  88708. Skeleton.prototype.getAnimationRange = function (name) {
  88709. return this._ranges[name];
  88710. };
  88711. /**
  88712. * Gets the list of all animation ranges defined on this skeleton
  88713. * @returns an array
  88714. */
  88715. Skeleton.prototype.getAnimationRanges = function () {
  88716. var animationRanges = [];
  88717. var name;
  88718. var i = 0;
  88719. for (name in this._ranges) {
  88720. animationRanges[i] = this._ranges[name];
  88721. i++;
  88722. }
  88723. return animationRanges;
  88724. };
  88725. /**
  88726. * Copy animation range from a source skeleton.
  88727. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  88728. * @param source defines the source skeleton
  88729. * @param name defines the name of the range to copy
  88730. * @param rescaleAsRequired defines if rescaling must be applied if required
  88731. * @returns true if operation was successful
  88732. */
  88733. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  88734. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  88735. if (this._ranges[name] || !source.getAnimationRange(name)) {
  88736. return false;
  88737. }
  88738. var ret = true;
  88739. var frameOffset = this._getHighestAnimationFrame() + 1;
  88740. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  88741. var boneDict = {};
  88742. var sourceBones = source.bones;
  88743. var nBones;
  88744. var i;
  88745. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  88746. boneDict[sourceBones[i].name] = sourceBones[i];
  88747. }
  88748. if (this.bones.length !== sourceBones.length) {
  88749. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  88750. ret = false;
  88751. }
  88752. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  88753. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  88754. var boneName = this.bones[i].name;
  88755. var sourceBone = boneDict[boneName];
  88756. if (sourceBone) {
  88757. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  88758. }
  88759. else {
  88760. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  88761. ret = false;
  88762. }
  88763. }
  88764. // do not call createAnimationRange(), since it also is done to bones, which was already done
  88765. var range = source.getAnimationRange(name);
  88766. if (range) {
  88767. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  88768. }
  88769. return ret;
  88770. };
  88771. /**
  88772. * Forces the skeleton to go to rest pose
  88773. */
  88774. Skeleton.prototype.returnToRest = function () {
  88775. for (var index = 0; index < this.bones.length; index++) {
  88776. this.bones[index].returnToRest();
  88777. }
  88778. };
  88779. Skeleton.prototype._getHighestAnimationFrame = function () {
  88780. var ret = 0;
  88781. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  88782. if (this.bones[i].animations[0]) {
  88783. var highest = this.bones[i].animations[0].getHighestFrame();
  88784. if (ret < highest) {
  88785. ret = highest;
  88786. }
  88787. }
  88788. }
  88789. return ret;
  88790. };
  88791. /**
  88792. * Begin a specific animation range
  88793. * @param name defines the name of the range to start
  88794. * @param loop defines if looping must be turned on (false by default)
  88795. * @param speedRatio defines the speed ratio to apply (1 by default)
  88796. * @param onAnimationEnd defines a callback which will be called when animation will end
  88797. * @returns a new animatable
  88798. */
  88799. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  88800. var range = this.getAnimationRange(name);
  88801. if (!range) {
  88802. return null;
  88803. }
  88804. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  88805. };
  88806. /** @hidden */
  88807. Skeleton.prototype._markAsDirty = function () {
  88808. this._isDirty = true;
  88809. };
  88810. /** @hidden */
  88811. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  88812. this._meshesWithPoseMatrix.push(mesh);
  88813. };
  88814. /** @hidden */
  88815. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  88816. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  88817. if (index > -1) {
  88818. this._meshesWithPoseMatrix.splice(index, 1);
  88819. }
  88820. };
  88821. /** @hidden */
  88822. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  88823. this.onBeforeComputeObservable.notifyObservers(this);
  88824. for (var index = 0; index < this.bones.length; index++) {
  88825. var bone = this.bones[index];
  88826. var parentBone = bone.getParent();
  88827. if (parentBone) {
  88828. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  88829. }
  88830. else {
  88831. if (initialSkinMatrix) {
  88832. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  88833. }
  88834. else {
  88835. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  88836. }
  88837. }
  88838. if (bone._index !== -1) {
  88839. var mappedIndex = bone._index === null ? index : bone._index;
  88840. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  88841. }
  88842. }
  88843. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  88844. };
  88845. /**
  88846. * Build all resources required to render a skeleton
  88847. */
  88848. Skeleton.prototype.prepare = function () {
  88849. if (!this._isDirty) {
  88850. return;
  88851. }
  88852. if (this.needInitialSkinMatrix) {
  88853. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  88854. var mesh = this._meshesWithPoseMatrix[index];
  88855. var poseMatrix = mesh.getPoseMatrix();
  88856. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  88857. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88858. }
  88859. if (this._synchronizedWithMesh !== mesh) {
  88860. this._synchronizedWithMesh = mesh;
  88861. // Prepare bones
  88862. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  88863. var bone = this.bones[boneIndex];
  88864. if (!bone.getParent()) {
  88865. var matrix = bone.getBaseMatrix();
  88866. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  88867. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  88868. }
  88869. }
  88870. }
  88871. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  88872. }
  88873. }
  88874. else {
  88875. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  88876. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  88877. }
  88878. this._computeTransformMatrices(this._transformMatrices, null);
  88879. }
  88880. this._isDirty = false;
  88881. this._scene._activeBones.addCount(this.bones.length, false);
  88882. };
  88883. /**
  88884. * Gets the list of animatables currently running for this skeleton
  88885. * @returns an array of animatables
  88886. */
  88887. Skeleton.prototype.getAnimatables = function () {
  88888. if (!this._animatables || this._animatables.length !== this.bones.length) {
  88889. this._animatables = [];
  88890. for (var index = 0; index < this.bones.length; index++) {
  88891. this._animatables.push(this.bones[index]);
  88892. }
  88893. }
  88894. return this._animatables;
  88895. };
  88896. /**
  88897. * Clone the current skeleton
  88898. * @param name defines the name of the new skeleton
  88899. * @param id defines the id of the enw skeleton
  88900. * @returns the new skeleton
  88901. */
  88902. Skeleton.prototype.clone = function (name, id) {
  88903. var result = new Skeleton(name, id || name, this._scene);
  88904. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88905. for (var index = 0; index < this.bones.length; index++) {
  88906. var source = this.bones[index];
  88907. var parentBone = null;
  88908. var parent_1 = source.getParent();
  88909. if (parent_1) {
  88910. var parentIndex = this.bones.indexOf(parent_1);
  88911. parentBone = result.bones[parentIndex];
  88912. }
  88913. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  88914. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  88915. }
  88916. if (this._ranges) {
  88917. result._ranges = {};
  88918. for (var rangeName in this._ranges) {
  88919. var range = this._ranges[rangeName];
  88920. if (range) {
  88921. result._ranges[rangeName] = range.clone();
  88922. }
  88923. }
  88924. }
  88925. this._isDirty = true;
  88926. return result;
  88927. };
  88928. /**
  88929. * Enable animation blending for this skeleton
  88930. * @param blendingSpeed defines the blending speed to apply
  88931. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  88932. */
  88933. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88934. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88935. this.bones.forEach(function (bone) {
  88936. bone.animations.forEach(function (animation) {
  88937. animation.enableBlending = true;
  88938. animation.blendingSpeed = blendingSpeed;
  88939. });
  88940. });
  88941. };
  88942. /**
  88943. * Releases all resources associated with the current skeleton
  88944. */
  88945. Skeleton.prototype.dispose = function () {
  88946. this._meshesWithPoseMatrix = [];
  88947. // Animations
  88948. this.getScene().stopAnimation(this);
  88949. // Remove from scene
  88950. this.getScene().removeSkeleton(this);
  88951. };
  88952. /**
  88953. * Serialize the skeleton in a JSON object
  88954. * @returns a JSON object
  88955. */
  88956. Skeleton.prototype.serialize = function () {
  88957. var serializationObject = {};
  88958. serializationObject.name = this.name;
  88959. serializationObject.id = this.id;
  88960. if (this.dimensionsAtRest) {
  88961. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88962. }
  88963. serializationObject.bones = [];
  88964. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88965. for (var index = 0; index < this.bones.length; index++) {
  88966. var bone = this.bones[index];
  88967. var parent_2 = bone.getParent();
  88968. var serializedBone = {
  88969. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88970. name: bone.name,
  88971. matrix: bone.getBaseMatrix().toArray(),
  88972. rest: bone.getRestPose().toArray()
  88973. };
  88974. serializationObject.bones.push(serializedBone);
  88975. if (bone.length) {
  88976. serializedBone.length = bone.length;
  88977. }
  88978. if (bone.metadata) {
  88979. serializedBone.metadata = bone.metadata;
  88980. }
  88981. if (bone.animations && bone.animations.length > 0) {
  88982. serializedBone.animation = bone.animations[0].serialize();
  88983. }
  88984. serializationObject.ranges = [];
  88985. for (var name in this._ranges) {
  88986. var source = this._ranges[name];
  88987. if (!source) {
  88988. continue;
  88989. }
  88990. var range = {};
  88991. range.name = name;
  88992. range.from = source.from;
  88993. range.to = source.to;
  88994. serializationObject.ranges.push(range);
  88995. }
  88996. }
  88997. return serializationObject;
  88998. };
  88999. /**
  89000. * Creates a new skeleton from serialized data
  89001. * @param parsedSkeleton defines the serialized data
  89002. * @param scene defines the hosting scene
  89003. * @returns a new skeleton
  89004. */
  89005. Skeleton.Parse = function (parsedSkeleton, scene) {
  89006. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  89007. if (parsedSkeleton.dimensionsAtRest) {
  89008. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  89009. }
  89010. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  89011. var index;
  89012. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  89013. var parsedBone = parsedSkeleton.bones[index];
  89014. var parentBone = null;
  89015. if (parsedBone.parentBoneIndex > -1) {
  89016. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  89017. }
  89018. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  89019. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  89020. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  89021. bone.id = parsedBone.id;
  89022. }
  89023. if (parsedBone.length) {
  89024. bone.length = parsedBone.length;
  89025. }
  89026. if (parsedBone.metadata) {
  89027. bone.metadata = parsedBone.metadata;
  89028. }
  89029. if (parsedBone.animation) {
  89030. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  89031. }
  89032. }
  89033. // placed after bones, so createAnimationRange can cascade down
  89034. if (parsedSkeleton.ranges) {
  89035. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  89036. var data = parsedSkeleton.ranges[index];
  89037. skeleton.createAnimationRange(data.name, data.from, data.to);
  89038. }
  89039. }
  89040. return skeleton;
  89041. };
  89042. /**
  89043. * Compute all node absolute transforms
  89044. * @param forceUpdate defines if computation must be done even if cache is up to date
  89045. */
  89046. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  89047. if (forceUpdate === void 0) { forceUpdate = false; }
  89048. var renderId = this._scene.getRenderId();
  89049. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  89050. this.bones[0].computeAbsoluteTransforms();
  89051. this._lastAbsoluteTransformsUpdateId = renderId;
  89052. }
  89053. };
  89054. /**
  89055. * Gets the root pose matrix
  89056. * @returns a matrix
  89057. */
  89058. Skeleton.prototype.getPoseMatrix = function () {
  89059. var poseMatrix = null;
  89060. if (this._meshesWithPoseMatrix.length > 0) {
  89061. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  89062. }
  89063. return poseMatrix;
  89064. };
  89065. /**
  89066. * Sorts bones per internal index
  89067. */
  89068. Skeleton.prototype.sortBones = function () {
  89069. var bones = new Array();
  89070. var visited = new Array(this.bones.length);
  89071. for (var index = 0; index < this.bones.length; index++) {
  89072. this._sortBones(index, bones, visited);
  89073. }
  89074. this.bones = bones;
  89075. };
  89076. Skeleton.prototype._sortBones = function (index, bones, visited) {
  89077. if (visited[index]) {
  89078. return;
  89079. }
  89080. visited[index] = true;
  89081. var bone = this.bones[index];
  89082. if (bone._index === undefined) {
  89083. bone._index = index;
  89084. }
  89085. var parentBone = bone.getParent();
  89086. if (parentBone) {
  89087. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  89088. }
  89089. bones.push(bone);
  89090. };
  89091. return Skeleton;
  89092. }());
  89093. BABYLON.Skeleton = Skeleton;
  89094. })(BABYLON || (BABYLON = {}));
  89095. //# sourceMappingURL=babylon.skeleton.js.map
  89096. var BABYLON;
  89097. (function (BABYLON) {
  89098. ;
  89099. /**
  89100. * This groups tools to convert HDR texture to native colors array.
  89101. */
  89102. var HDRTools = /** @class */ (function () {
  89103. function HDRTools() {
  89104. }
  89105. HDRTools.Ldexp = function (mantissa, exponent) {
  89106. if (exponent > 1023) {
  89107. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  89108. }
  89109. if (exponent < -1074) {
  89110. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  89111. }
  89112. return mantissa * Math.pow(2, exponent);
  89113. };
  89114. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  89115. if (exponent > 0) { /*nonzero pixel*/
  89116. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  89117. float32array[index + 0] = red * exponent;
  89118. float32array[index + 1] = green * exponent;
  89119. float32array[index + 2] = blue * exponent;
  89120. }
  89121. else {
  89122. float32array[index + 0] = 0;
  89123. float32array[index + 1] = 0;
  89124. float32array[index + 2] = 0;
  89125. }
  89126. };
  89127. HDRTools.readStringLine = function (uint8array, startIndex) {
  89128. var line = "";
  89129. var character = "";
  89130. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  89131. character = String.fromCharCode(uint8array[i]);
  89132. if (character == "\n") {
  89133. break;
  89134. }
  89135. line += character;
  89136. }
  89137. return line;
  89138. };
  89139. /**
  89140. * Reads header information from an RGBE texture stored in a native array.
  89141. * More information on this format are available here:
  89142. * https://en.wikipedia.org/wiki/RGBE_image_format
  89143. *
  89144. * @param uint8array The binary file stored in native array.
  89145. * @return The header information.
  89146. */
  89147. HDRTools.RGBE_ReadHeader = function (uint8array) {
  89148. var height = 0;
  89149. var width = 0;
  89150. var line = this.readStringLine(uint8array, 0);
  89151. if (line[0] != '#' || line[1] != '?') {
  89152. throw "Bad HDR Format.";
  89153. }
  89154. var endOfHeader = false;
  89155. var findFormat = false;
  89156. var lineIndex = 0;
  89157. do {
  89158. lineIndex += (line.length + 1);
  89159. line = this.readStringLine(uint8array, lineIndex);
  89160. if (line == "FORMAT=32-bit_rle_rgbe") {
  89161. findFormat = true;
  89162. }
  89163. else if (line.length == 0) {
  89164. endOfHeader = true;
  89165. }
  89166. } while (!endOfHeader);
  89167. if (!findFormat) {
  89168. throw "HDR Bad header format, unsupported FORMAT";
  89169. }
  89170. lineIndex += (line.length + 1);
  89171. line = this.readStringLine(uint8array, lineIndex);
  89172. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  89173. var match = sizeRegexp.exec(line);
  89174. // TODO. Support +Y and -X if needed.
  89175. if (!match || match.length < 3) {
  89176. throw "HDR Bad header format, no size";
  89177. }
  89178. width = parseInt(match[2]);
  89179. height = parseInt(match[1]);
  89180. if (width < 8 || width > 0x7fff) {
  89181. throw "HDR Bad header format, unsupported size";
  89182. }
  89183. lineIndex += (line.length + 1);
  89184. return {
  89185. height: height,
  89186. width: width,
  89187. dataPosition: lineIndex
  89188. };
  89189. };
  89190. /**
  89191. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  89192. * This RGBE texture needs to store the information as a panorama.
  89193. *
  89194. * More information on this format are available here:
  89195. * https://en.wikipedia.org/wiki/RGBE_image_format
  89196. *
  89197. * @param buffer The binary file stored in an array buffer.
  89198. * @param size The expected size of the extracted cubemap.
  89199. * @return The Cube Map information.
  89200. */
  89201. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  89202. var uint8array = new Uint8Array(buffer);
  89203. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  89204. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89205. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  89206. return cubeMapData;
  89207. };
  89208. /**
  89209. * Returns the pixels data extracted from an RGBE texture.
  89210. * This pixels will be stored left to right up to down in the R G B order in one array.
  89211. *
  89212. * More information on this format are available here:
  89213. * https://en.wikipedia.org/wiki/RGBE_image_format
  89214. *
  89215. * @param uint8array The binary file stored in an array buffer.
  89216. * @param hdrInfo The header information of the file.
  89217. * @return The pixels data in RGB right to left up to down order.
  89218. */
  89219. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  89220. // Keep for multi format supports.
  89221. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  89222. };
  89223. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  89224. var num_scanlines = hdrInfo.height;
  89225. var scanline_width = hdrInfo.width;
  89226. var a, b, c, d, count;
  89227. var dataIndex = hdrInfo.dataPosition;
  89228. var index = 0, endIndex = 0, i = 0;
  89229. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  89230. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  89231. // 3 channels of 4 bytes per pixel in float.
  89232. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  89233. var resultArray = new Float32Array(resultBuffer);
  89234. // read in each successive scanline
  89235. while (num_scanlines > 0) {
  89236. a = uint8array[dataIndex++];
  89237. b = uint8array[dataIndex++];
  89238. c = uint8array[dataIndex++];
  89239. d = uint8array[dataIndex++];
  89240. if (a != 2 || b != 2 || (c & 0x80)) {
  89241. // this file is not run length encoded
  89242. throw "HDR Bad header format, not RLE";
  89243. }
  89244. if (((c << 8) | d) != scanline_width) {
  89245. throw "HDR Bad header format, wrong scan line width";
  89246. }
  89247. index = 0;
  89248. // read each of the four channels for the scanline into the buffer
  89249. for (i = 0; i < 4; i++) {
  89250. endIndex = (i + 1) * scanline_width;
  89251. while (index < endIndex) {
  89252. a = uint8array[dataIndex++];
  89253. b = uint8array[dataIndex++];
  89254. if (a > 128) {
  89255. // a run of the same value
  89256. count = a - 128;
  89257. if ((count == 0) || (count > endIndex - index)) {
  89258. throw "HDR Bad Format, bad scanline data (run)";
  89259. }
  89260. while (count-- > 0) {
  89261. scanLineArray[index++] = b;
  89262. }
  89263. }
  89264. else {
  89265. // a non-run
  89266. count = a;
  89267. if ((count == 0) || (count > endIndex - index)) {
  89268. throw "HDR Bad Format, bad scanline data (non-run)";
  89269. }
  89270. scanLineArray[index++] = b;
  89271. if (--count > 0) {
  89272. for (var j = 0; j < count; j++) {
  89273. scanLineArray[index++] = uint8array[dataIndex++];
  89274. }
  89275. }
  89276. }
  89277. }
  89278. }
  89279. // now convert data from buffer into floats
  89280. for (i = 0; i < scanline_width; i++) {
  89281. a = scanLineArray[i];
  89282. b = scanLineArray[i + scanline_width];
  89283. c = scanLineArray[i + 2 * scanline_width];
  89284. d = scanLineArray[i + 3 * scanline_width];
  89285. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  89286. }
  89287. num_scanlines--;
  89288. }
  89289. return resultArray;
  89290. };
  89291. return HDRTools;
  89292. }());
  89293. BABYLON.HDRTools = HDRTools;
  89294. })(BABYLON || (BABYLON = {}));
  89295. //# sourceMappingURL=babylon.hdr.js.map
  89296. var BABYLON;
  89297. (function (BABYLON) {
  89298. /**
  89299. * This represents a texture coming from an HDR input.
  89300. *
  89301. * The only supported format is currently panorama picture stored in RGBE format.
  89302. * Example of such files can be found on HDRLib: http://hdrlib.com/
  89303. */
  89304. var HDRCubeTexture = /** @class */ (function (_super) {
  89305. __extends(HDRCubeTexture, _super);
  89306. /**
  89307. * Instantiates an HDRTexture from the following parameters.
  89308. *
  89309. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  89310. * @param scene The scene the texture will be used in
  89311. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  89312. * @param noMipmap Forces to not generate the mipmap if true
  89313. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  89314. * @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)
  89315. * @param reserved Reserved flag for internal use.
  89316. */
  89317. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  89318. if (noMipmap === void 0) { noMipmap = false; }
  89319. if (generateHarmonics === void 0) { generateHarmonics = true; }
  89320. if (gammaSpace === void 0) { gammaSpace = false; }
  89321. if (reserved === void 0) { reserved = false; }
  89322. if (onLoad === void 0) { onLoad = null; }
  89323. if (onError === void 0) { onError = null; }
  89324. var _this = _super.call(this, scene) || this;
  89325. _this._generateHarmonics = true;
  89326. _this._onLoad = null;
  89327. _this._onError = null;
  89328. /**
  89329. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  89330. */
  89331. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  89332. _this._isBlocking = true;
  89333. _this._rotationY = 0;
  89334. /**
  89335. * Gets or sets the center of the bounding box associated with the cube texture
  89336. * It must define where the camera used to render the texture was set
  89337. */
  89338. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  89339. if (!url) {
  89340. return _this;
  89341. }
  89342. _this.name = url;
  89343. _this.url = url;
  89344. _this.hasAlpha = false;
  89345. _this.isCube = true;
  89346. _this._textureMatrix = BABYLON.Matrix.Identity();
  89347. _this._onLoad = onLoad;
  89348. _this._onError = onError;
  89349. _this.gammaSpace = gammaSpace;
  89350. _this._noMipmap = noMipmap;
  89351. _this._size = size;
  89352. _this._texture = _this._getFromCache(url, _this._noMipmap);
  89353. if (!_this._texture) {
  89354. if (!scene.useDelayedTextureLoading) {
  89355. _this.loadTexture();
  89356. }
  89357. else {
  89358. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  89359. }
  89360. }
  89361. return _this;
  89362. }
  89363. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  89364. /**
  89365. * Gets wether or not the texture is blocking during loading.
  89366. */
  89367. get: function () {
  89368. return this._isBlocking;
  89369. },
  89370. /**
  89371. * Sets wether or not the texture is blocking during loading.
  89372. */
  89373. set: function (value) {
  89374. this._isBlocking = value;
  89375. },
  89376. enumerable: true,
  89377. configurable: true
  89378. });
  89379. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  89380. /**
  89381. * Gets texture matrix rotation angle around Y axis radians.
  89382. */
  89383. get: function () {
  89384. return this._rotationY;
  89385. },
  89386. /**
  89387. * Sets texture matrix rotation angle around Y axis in radians.
  89388. */
  89389. set: function (value) {
  89390. this._rotationY = value;
  89391. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  89392. },
  89393. enumerable: true,
  89394. configurable: true
  89395. });
  89396. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  89397. get: function () {
  89398. return this._boundingBoxSize;
  89399. },
  89400. /**
  89401. * Gets or sets the size of the bounding box associated with the cube texture
  89402. * When defined, the cubemap will switch to local mode
  89403. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  89404. * @example https://www.babylonjs-playground.com/#RNASML
  89405. */
  89406. set: function (value) {
  89407. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  89408. return;
  89409. }
  89410. this._boundingBoxSize = value;
  89411. var scene = this.getScene();
  89412. if (scene) {
  89413. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  89414. }
  89415. },
  89416. enumerable: true,
  89417. configurable: true
  89418. });
  89419. /**
  89420. * Occurs when the file is raw .hdr file.
  89421. */
  89422. HDRCubeTexture.prototype.loadTexture = function () {
  89423. var _this = this;
  89424. var callback = function (buffer) {
  89425. _this.lodGenerationOffset = 0.0;
  89426. _this.lodGenerationScale = 0.8;
  89427. var scene = _this.getScene();
  89428. if (!scene) {
  89429. return null;
  89430. }
  89431. // Extract the raw linear data.
  89432. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  89433. // Generate harmonics if needed.
  89434. if (_this._generateHarmonics) {
  89435. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  89436. _this.sphericalPolynomial = sphericalPolynomial;
  89437. }
  89438. var results = [];
  89439. var byteArray = null;
  89440. // Push each faces.
  89441. for (var j = 0; j < 6; j++) {
  89442. // Create uintarray fallback.
  89443. if (!scene.getEngine().getCaps().textureFloat) {
  89444. // 3 channels of 1 bytes per pixel in bytes.
  89445. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  89446. byteArray = new Uint8Array(byteBuffer);
  89447. }
  89448. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  89449. // If special cases.
  89450. if (_this.gammaSpace || byteArray) {
  89451. for (var i = 0; i < _this._size * _this._size; i++) {
  89452. // Put in gamma space if requested.
  89453. if (_this.gammaSpace) {
  89454. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  89455. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  89456. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  89457. }
  89458. // Convert to int texture for fallback.
  89459. if (byteArray) {
  89460. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  89461. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  89462. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  89463. // May use luminance instead if the result is not accurate.
  89464. var max = Math.max(Math.max(r, g), b);
  89465. if (max > 255) {
  89466. var scale = 255 / max;
  89467. r *= scale;
  89468. g *= scale;
  89469. b *= scale;
  89470. }
  89471. byteArray[(i * 3) + 0] = r;
  89472. byteArray[(i * 3) + 1] = g;
  89473. byteArray[(i * 3) + 2] = b;
  89474. }
  89475. }
  89476. }
  89477. if (byteArray) {
  89478. results.push(byteArray);
  89479. }
  89480. else {
  89481. results.push(dataFace);
  89482. }
  89483. }
  89484. return results;
  89485. };
  89486. var scene = this.getScene();
  89487. if (scene) {
  89488. 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);
  89489. }
  89490. };
  89491. HDRCubeTexture.prototype.clone = function () {
  89492. var scene = this.getScene();
  89493. if (!scene) {
  89494. return this;
  89495. }
  89496. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  89497. // Base texture
  89498. newTexture.level = this.level;
  89499. newTexture.wrapU = this.wrapU;
  89500. newTexture.wrapV = this.wrapV;
  89501. newTexture.coordinatesIndex = this.coordinatesIndex;
  89502. newTexture.coordinatesMode = this.coordinatesMode;
  89503. return newTexture;
  89504. };
  89505. // Methods
  89506. HDRCubeTexture.prototype.delayLoad = function () {
  89507. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  89508. return;
  89509. }
  89510. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  89511. this._texture = this._getFromCache(this.url, this._noMipmap);
  89512. if (!this._texture) {
  89513. this.loadTexture();
  89514. }
  89515. };
  89516. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  89517. return this._textureMatrix;
  89518. };
  89519. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  89520. this._textureMatrix = value;
  89521. };
  89522. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  89523. var texture = null;
  89524. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  89525. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  89526. texture.name = parsedTexture.name;
  89527. texture.hasAlpha = parsedTexture.hasAlpha;
  89528. texture.level = parsedTexture.level;
  89529. texture.coordinatesMode = parsedTexture.coordinatesMode;
  89530. texture.isBlocking = parsedTexture.isBlocking;
  89531. }
  89532. if (texture) {
  89533. if (parsedTexture.boundingBoxPosition) {
  89534. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  89535. }
  89536. if (parsedTexture.boundingBoxSize) {
  89537. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  89538. }
  89539. if (parsedTexture.rotationY) {
  89540. texture.rotationY = parsedTexture.rotationY;
  89541. }
  89542. }
  89543. return texture;
  89544. };
  89545. HDRCubeTexture.prototype.serialize = function () {
  89546. if (!this.name) {
  89547. return null;
  89548. }
  89549. var serializationObject = {};
  89550. serializationObject.name = this.name;
  89551. serializationObject.hasAlpha = this.hasAlpha;
  89552. serializationObject.isCube = true;
  89553. serializationObject.level = this.level;
  89554. serializationObject.size = this._size;
  89555. serializationObject.coordinatesMode = this.coordinatesMode;
  89556. serializationObject.useInGammaSpace = this.gammaSpace;
  89557. serializationObject.generateHarmonics = this._generateHarmonics;
  89558. serializationObject.customType = "BABYLON.HDRCubeTexture";
  89559. serializationObject.noMipmap = this._noMipmap;
  89560. serializationObject.isBlocking = this._isBlocking;
  89561. serializationObject.rotationY = this._rotationY;
  89562. return serializationObject;
  89563. };
  89564. HDRCubeTexture._facesMapping = [
  89565. "right",
  89566. "left",
  89567. "up",
  89568. "down",
  89569. "front",
  89570. "back"
  89571. ];
  89572. return HDRCubeTexture;
  89573. }(BABYLON.BaseTexture));
  89574. BABYLON.HDRCubeTexture = HDRCubeTexture;
  89575. })(BABYLON || (BABYLON = {}));
  89576. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  89577. var BABYLON;
  89578. (function (BABYLON) {
  89579. /**
  89580. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  89581. */
  89582. var PanoramaToCubeMapTools = /** @class */ (function () {
  89583. function PanoramaToCubeMapTools() {
  89584. }
  89585. /**
  89586. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  89587. *
  89588. * @param float32Array The source data.
  89589. * @param inputWidth The width of the input panorama.
  89590. * @param inputhHeight The height of the input panorama.
  89591. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  89592. * @return The cubemap data
  89593. */
  89594. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  89595. if (!float32Array) {
  89596. throw "ConvertPanoramaToCubemap: input cannot be null";
  89597. }
  89598. if (float32Array.length != inputWidth * inputHeight * 3) {
  89599. throw "ConvertPanoramaToCubemap: input size is wrong";
  89600. }
  89601. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  89602. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  89603. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  89604. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  89605. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  89606. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  89607. return {
  89608. front: textureFront,
  89609. back: textureBack,
  89610. left: textureLeft,
  89611. right: textureRight,
  89612. up: textureUp,
  89613. down: textureDown,
  89614. size: size,
  89615. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89616. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  89617. gammaSpace: false,
  89618. };
  89619. };
  89620. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  89621. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  89622. var textureArray = new Float32Array(buffer);
  89623. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  89624. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  89625. var dy = 1 / texSize;
  89626. var fy = 0;
  89627. for (var y = 0; y < texSize; y++) {
  89628. var xv1 = faceData[0];
  89629. var xv2 = faceData[2];
  89630. for (var x = 0; x < texSize; x++) {
  89631. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  89632. v.normalize();
  89633. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  89634. // 3 channels per pixels
  89635. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  89636. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  89637. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  89638. xv1 = xv1.add(rotDX1);
  89639. xv2 = xv2.add(rotDX2);
  89640. }
  89641. fy += dy;
  89642. }
  89643. return textureArray;
  89644. };
  89645. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  89646. var theta = Math.atan2(vDir.z, vDir.x);
  89647. var phi = Math.acos(vDir.y);
  89648. while (theta < -Math.PI)
  89649. theta += 2 * Math.PI;
  89650. while (theta > Math.PI)
  89651. theta -= 2 * Math.PI;
  89652. var dx = theta / Math.PI;
  89653. var dy = phi / Math.PI;
  89654. // recenter.
  89655. dx = dx * 0.5 + 0.5;
  89656. var px = Math.round(dx * inputWidth);
  89657. if (px < 0)
  89658. px = 0;
  89659. else if (px >= inputWidth)
  89660. px = inputWidth - 1;
  89661. var py = Math.round(dy * inputHeight);
  89662. if (py < 0)
  89663. py = 0;
  89664. else if (py >= inputHeight)
  89665. py = inputHeight - 1;
  89666. var inputY = (inputHeight - py - 1);
  89667. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  89668. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  89669. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  89670. return {
  89671. r: r,
  89672. g: g,
  89673. b: b
  89674. };
  89675. };
  89676. PanoramaToCubeMapTools.FACE_FRONT = [
  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. new BABYLON.Vector3(1.0, 1.0, -1.0)
  89681. ];
  89682. PanoramaToCubeMapTools.FACE_BACK = [
  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. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  89687. ];
  89688. PanoramaToCubeMapTools.FACE_RIGHT = [
  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. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89693. ];
  89694. PanoramaToCubeMapTools.FACE_LEFT = [
  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. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  89699. ];
  89700. PanoramaToCubeMapTools.FACE_DOWN = [
  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. new BABYLON.Vector3(1.0, 1.0, 1.0)
  89705. ];
  89706. PanoramaToCubeMapTools.FACE_UP = [
  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. new BABYLON.Vector3(1.0, -1.0, -1.0)
  89711. ];
  89712. return PanoramaToCubeMapTools;
  89713. }());
  89714. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  89715. })(BABYLON || (BABYLON = {}));
  89716. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  89717. var BABYLON;
  89718. (function (BABYLON) {
  89719. var IndexedVector2 = /** @class */ (function (_super) {
  89720. __extends(IndexedVector2, _super);
  89721. function IndexedVector2(original, index) {
  89722. var _this = _super.call(this, original.x, original.y) || this;
  89723. _this.index = index;
  89724. return _this;
  89725. }
  89726. return IndexedVector2;
  89727. }(BABYLON.Vector2));
  89728. var PolygonPoints = /** @class */ (function () {
  89729. function PolygonPoints() {
  89730. this.elements = new Array();
  89731. }
  89732. PolygonPoints.prototype.add = function (originalPoints) {
  89733. var _this = this;
  89734. var result = new Array();
  89735. originalPoints.forEach(function (point) {
  89736. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  89737. var newPoint = new IndexedVector2(point, _this.elements.length);
  89738. result.push(newPoint);
  89739. _this.elements.push(newPoint);
  89740. }
  89741. });
  89742. return result;
  89743. };
  89744. PolygonPoints.prototype.computeBounds = function () {
  89745. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89746. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  89747. this.elements.forEach(function (point) {
  89748. // x
  89749. if (point.x < lmin.x) {
  89750. lmin.x = point.x;
  89751. }
  89752. else if (point.x > lmax.x) {
  89753. lmax.x = point.x;
  89754. }
  89755. // y
  89756. if (point.y < lmin.y) {
  89757. lmin.y = point.y;
  89758. }
  89759. else if (point.y > lmax.y) {
  89760. lmax.y = point.y;
  89761. }
  89762. });
  89763. return {
  89764. min: lmin,
  89765. max: lmax,
  89766. width: lmax.x - lmin.x,
  89767. height: lmax.y - lmin.y
  89768. };
  89769. };
  89770. return PolygonPoints;
  89771. }());
  89772. var Polygon = /** @class */ (function () {
  89773. function Polygon() {
  89774. }
  89775. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  89776. return [
  89777. new BABYLON.Vector2(xmin, ymin),
  89778. new BABYLON.Vector2(xmax, ymin),
  89779. new BABYLON.Vector2(xmax, ymax),
  89780. new BABYLON.Vector2(xmin, ymax)
  89781. ];
  89782. };
  89783. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  89784. if (cx === void 0) { cx = 0; }
  89785. if (cy === void 0) { cy = 0; }
  89786. if (numberOfSides === void 0) { numberOfSides = 32; }
  89787. var result = new Array();
  89788. var angle = 0;
  89789. var increment = (Math.PI * 2) / numberOfSides;
  89790. for (var i = 0; i < numberOfSides; i++) {
  89791. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  89792. angle -= increment;
  89793. }
  89794. return result;
  89795. };
  89796. Polygon.Parse = function (input) {
  89797. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  89798. var i, result = [];
  89799. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  89800. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  89801. }
  89802. return result;
  89803. };
  89804. Polygon.StartingAt = function (x, y) {
  89805. return BABYLON.Path2.StartingAt(x, y);
  89806. };
  89807. return Polygon;
  89808. }());
  89809. BABYLON.Polygon = Polygon;
  89810. var PolygonMeshBuilder = /** @class */ (function () {
  89811. function PolygonMeshBuilder(name, contours, scene) {
  89812. this._points = new PolygonPoints();
  89813. this._outlinepoints = new PolygonPoints();
  89814. this._holes = new Array();
  89815. this._epoints = new Array();
  89816. this._eholes = new Array();
  89817. this._name = name;
  89818. this._scene = scene;
  89819. var points;
  89820. if (contours instanceof BABYLON.Path2) {
  89821. points = contours.getPoints();
  89822. }
  89823. else {
  89824. points = contours;
  89825. }
  89826. this._addToepoint(points);
  89827. this._points.add(points);
  89828. this._outlinepoints.add(points);
  89829. if (typeof earcut === 'undefined') {
  89830. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  89831. }
  89832. }
  89833. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  89834. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  89835. var p = points_1[_i];
  89836. this._epoints.push(p.x, p.y);
  89837. }
  89838. };
  89839. PolygonMeshBuilder.prototype.addHole = function (hole) {
  89840. this._points.add(hole);
  89841. var holepoints = new PolygonPoints();
  89842. holepoints.add(hole);
  89843. this._holes.push(holepoints);
  89844. this._eholes.push(this._epoints.length / 2);
  89845. this._addToepoint(hole);
  89846. return this;
  89847. };
  89848. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  89849. var _this = this;
  89850. if (updatable === void 0) { updatable = false; }
  89851. if (depth === void 0) { depth = 0; }
  89852. var result = new BABYLON.Mesh(this._name, this._scene);
  89853. var normals = new Array();
  89854. var positions = new Array();
  89855. var uvs = new Array();
  89856. var bounds = this._points.computeBounds();
  89857. this._points.elements.forEach(function (p) {
  89858. normals.push(0, 1.0, 0);
  89859. positions.push(p.x, 0, p.y);
  89860. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  89861. });
  89862. var indices = new Array();
  89863. var res = earcut(this._epoints, this._eholes, 2);
  89864. for (var i = 0; i < res.length; i++) {
  89865. indices.push(res[i]);
  89866. }
  89867. if (depth > 0) {
  89868. var positionscount = (positions.length / 3); //get the current pointcount
  89869. this._points.elements.forEach(function (p) {
  89870. normals.push(0, -1.0, 0);
  89871. positions.push(p.x, -depth, p.y);
  89872. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  89873. });
  89874. var totalCount = indices.length;
  89875. for (var i = 0; i < totalCount; i += 3) {
  89876. var i0 = indices[i + 0];
  89877. var i1 = indices[i + 1];
  89878. var i2 = indices[i + 2];
  89879. indices.push(i2 + positionscount);
  89880. indices.push(i1 + positionscount);
  89881. indices.push(i0 + positionscount);
  89882. }
  89883. //Add the sides
  89884. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  89885. this._holes.forEach(function (hole) {
  89886. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  89887. });
  89888. }
  89889. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  89890. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  89891. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  89892. result.setIndices(indices);
  89893. return result;
  89894. };
  89895. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  89896. var StartIndex = positions.length / 3;
  89897. var ulength = 0;
  89898. for (var i = 0; i < points.elements.length; i++) {
  89899. var p = points.elements[i];
  89900. var p1;
  89901. if ((i + 1) > points.elements.length - 1) {
  89902. p1 = points.elements[0];
  89903. }
  89904. else {
  89905. p1 = points.elements[i + 1];
  89906. }
  89907. positions.push(p.x, 0, p.y);
  89908. positions.push(p.x, -depth, p.y);
  89909. positions.push(p1.x, 0, p1.y);
  89910. positions.push(p1.x, -depth, p1.y);
  89911. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  89912. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  89913. var v3 = v2.subtract(v1);
  89914. var v4 = new BABYLON.Vector3(0, 1, 0);
  89915. var vn = BABYLON.Vector3.Cross(v3, v4);
  89916. vn = vn.normalize();
  89917. uvs.push(ulength / bounds.width, 0);
  89918. uvs.push(ulength / bounds.width, 1);
  89919. ulength += v3.length();
  89920. uvs.push((ulength / bounds.width), 0);
  89921. uvs.push((ulength / bounds.width), 1);
  89922. if (!flip) {
  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. normals.push(-vn.x, -vn.y, -vn.z);
  89927. indices.push(StartIndex);
  89928. indices.push(StartIndex + 1);
  89929. indices.push(StartIndex + 2);
  89930. indices.push(StartIndex + 1);
  89931. indices.push(StartIndex + 3);
  89932. indices.push(StartIndex + 2);
  89933. }
  89934. else {
  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. normals.push(vn.x, vn.y, vn.z);
  89939. indices.push(StartIndex);
  89940. indices.push(StartIndex + 2);
  89941. indices.push(StartIndex + 1);
  89942. indices.push(StartIndex + 1);
  89943. indices.push(StartIndex + 2);
  89944. indices.push(StartIndex + 3);
  89945. }
  89946. StartIndex += 4;
  89947. }
  89948. ;
  89949. };
  89950. return PolygonMeshBuilder;
  89951. }());
  89952. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89953. })(BABYLON || (BABYLON = {}));
  89954. //# sourceMappingURL=babylon.polygonMesh.js.map
  89955. var BABYLON;
  89956. (function (BABYLON) {
  89957. // Unique ID when we import meshes from Babylon to CSG
  89958. var currentCSGMeshId = 0;
  89959. // # class Vertex
  89960. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89961. // one to provide additional features like texture coordinates and vertex
  89962. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89963. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89964. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89965. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89966. // is not used anywhere else.
  89967. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89968. var Vertex = /** @class */ (function () {
  89969. function Vertex(pos, normal, uv) {
  89970. this.pos = pos;
  89971. this.normal = normal;
  89972. this.uv = uv;
  89973. }
  89974. Vertex.prototype.clone = function () {
  89975. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89976. };
  89977. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89978. // orientation of a polygon is flipped.
  89979. Vertex.prototype.flip = function () {
  89980. this.normal = this.normal.scale(-1);
  89981. };
  89982. // Create a new vertex between this vertex and `other` by linearly
  89983. // interpolating all properties using a parameter of `t`. Subclasses should
  89984. // override this to interpolate additional properties.
  89985. Vertex.prototype.interpolate = function (other, t) {
  89986. 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));
  89987. };
  89988. return Vertex;
  89989. }());
  89990. // # class Plane
  89991. // Represents a plane in 3D space.
  89992. var Plane = /** @class */ (function () {
  89993. function Plane(normal, w) {
  89994. this.normal = normal;
  89995. this.w = w;
  89996. }
  89997. Plane.FromPoints = function (a, b, c) {
  89998. var v0 = c.subtract(a);
  89999. var v1 = b.subtract(a);
  90000. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  90001. return null;
  90002. }
  90003. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  90004. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  90005. };
  90006. Plane.prototype.clone = function () {
  90007. return new Plane(this.normal.clone(), this.w);
  90008. };
  90009. Plane.prototype.flip = function () {
  90010. this.normal.scaleInPlace(-1);
  90011. this.w = -this.w;
  90012. };
  90013. // Split `polygon` by this plane if needed, then put the polygon or polygon
  90014. // fragments in the appropriate lists. Coplanar polygons go into either
  90015. // `coplanarFront` or `coplanarBack` depending on their orientation with
  90016. // respect to this plane. Polygons in front or in back of this plane go into
  90017. // either `front` or `back`.
  90018. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  90019. var COPLANAR = 0;
  90020. var FRONT = 1;
  90021. var BACK = 2;
  90022. var SPANNING = 3;
  90023. // Classify each point as well as the entire polygon into one of the above
  90024. // four classes.
  90025. var polygonType = 0;
  90026. var types = [];
  90027. var i;
  90028. var t;
  90029. for (i = 0; i < polygon.vertices.length; i++) {
  90030. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  90031. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  90032. polygonType |= type;
  90033. types.push(type);
  90034. }
  90035. // Put the polygon in the correct list, splitting it when necessary.
  90036. switch (polygonType) {
  90037. case COPLANAR:
  90038. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  90039. break;
  90040. case FRONT:
  90041. front.push(polygon);
  90042. break;
  90043. case BACK:
  90044. back.push(polygon);
  90045. break;
  90046. case SPANNING:
  90047. var f = [], b = [];
  90048. for (i = 0; i < polygon.vertices.length; i++) {
  90049. var j = (i + 1) % polygon.vertices.length;
  90050. var ti = types[i], tj = types[j];
  90051. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  90052. if (ti !== BACK)
  90053. f.push(vi);
  90054. if (ti !== FRONT)
  90055. b.push(ti !== BACK ? vi.clone() : vi);
  90056. if ((ti | tj) === SPANNING) {
  90057. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  90058. var v = vi.interpolate(vj, t);
  90059. f.push(v);
  90060. b.push(v.clone());
  90061. }
  90062. }
  90063. var poly;
  90064. if (f.length >= 3) {
  90065. poly = new Polygon(f, polygon.shared);
  90066. if (poly.plane)
  90067. front.push(poly);
  90068. }
  90069. if (b.length >= 3) {
  90070. poly = new Polygon(b, polygon.shared);
  90071. if (poly.plane)
  90072. back.push(poly);
  90073. }
  90074. break;
  90075. }
  90076. };
  90077. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  90078. // point is on the plane.
  90079. Plane.EPSILON = 1e-5;
  90080. return Plane;
  90081. }());
  90082. // # class Polygon
  90083. // Represents a convex polygon. The vertices used to initialize a polygon must
  90084. // be coplanar and form a convex loop.
  90085. //
  90086. // Each convex polygon has a `shared` property, which is shared between all
  90087. // polygons that are clones of each other or were split from the same polygon.
  90088. // This can be used to define per-polygon properties (such as surface color).
  90089. var Polygon = /** @class */ (function () {
  90090. function Polygon(vertices, shared) {
  90091. this.vertices = vertices;
  90092. this.shared = shared;
  90093. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  90094. }
  90095. Polygon.prototype.clone = function () {
  90096. var vertices = this.vertices.map(function (v) { return v.clone(); });
  90097. return new Polygon(vertices, this.shared);
  90098. };
  90099. Polygon.prototype.flip = function () {
  90100. this.vertices.reverse().map(function (v) { v.flip(); });
  90101. this.plane.flip();
  90102. };
  90103. return Polygon;
  90104. }());
  90105. // # class Node
  90106. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  90107. // by picking a polygon to split along. That polygon (and all other coplanar
  90108. // polygons) are added directly to that node and the other polygons are added to
  90109. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  90110. // no distinction between internal and leaf nodes.
  90111. var Node = /** @class */ (function () {
  90112. function Node(polygons) {
  90113. this.plane = null;
  90114. this.front = null;
  90115. this.back = null;
  90116. this.polygons = new Array();
  90117. if (polygons) {
  90118. this.build(polygons);
  90119. }
  90120. }
  90121. Node.prototype.clone = function () {
  90122. var node = new Node();
  90123. node.plane = this.plane && this.plane.clone();
  90124. node.front = this.front && this.front.clone();
  90125. node.back = this.back && this.back.clone();
  90126. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  90127. return node;
  90128. };
  90129. // Convert solid space to empty space and empty space to solid space.
  90130. Node.prototype.invert = function () {
  90131. for (var i = 0; i < this.polygons.length; i++) {
  90132. this.polygons[i].flip();
  90133. }
  90134. if (this.plane) {
  90135. this.plane.flip();
  90136. }
  90137. if (this.front) {
  90138. this.front.invert();
  90139. }
  90140. if (this.back) {
  90141. this.back.invert();
  90142. }
  90143. var temp = this.front;
  90144. this.front = this.back;
  90145. this.back = temp;
  90146. };
  90147. // Recursively remove all polygons in `polygons` that are inside this BSP
  90148. // tree.
  90149. Node.prototype.clipPolygons = function (polygons) {
  90150. if (!this.plane)
  90151. return polygons.slice();
  90152. var front = new Array(), back = new Array();
  90153. for (var i = 0; i < polygons.length; i++) {
  90154. this.plane.splitPolygon(polygons[i], front, back, front, back);
  90155. }
  90156. if (this.front) {
  90157. front = this.front.clipPolygons(front);
  90158. }
  90159. if (this.back) {
  90160. back = this.back.clipPolygons(back);
  90161. }
  90162. else {
  90163. back = [];
  90164. }
  90165. return front.concat(back);
  90166. };
  90167. // Remove all polygons in this BSP tree that are inside the other BSP tree
  90168. // `bsp`.
  90169. Node.prototype.clipTo = function (bsp) {
  90170. this.polygons = bsp.clipPolygons(this.polygons);
  90171. if (this.front)
  90172. this.front.clipTo(bsp);
  90173. if (this.back)
  90174. this.back.clipTo(bsp);
  90175. };
  90176. // Return a list of all polygons in this BSP tree.
  90177. Node.prototype.allPolygons = function () {
  90178. var polygons = this.polygons.slice();
  90179. if (this.front)
  90180. polygons = polygons.concat(this.front.allPolygons());
  90181. if (this.back)
  90182. polygons = polygons.concat(this.back.allPolygons());
  90183. return polygons;
  90184. };
  90185. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  90186. // new polygons are filtered down to the bottom of the tree and become new
  90187. // nodes there. Each set of polygons is partitioned using the first polygon
  90188. // (no heuristic is used to pick a good split).
  90189. Node.prototype.build = function (polygons) {
  90190. if (!polygons.length)
  90191. return;
  90192. if (!this.plane)
  90193. this.plane = polygons[0].plane.clone();
  90194. var front = new Array(), back = new Array();
  90195. for (var i = 0; i < polygons.length; i++) {
  90196. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  90197. }
  90198. if (front.length) {
  90199. if (!this.front)
  90200. this.front = new Node();
  90201. this.front.build(front);
  90202. }
  90203. if (back.length) {
  90204. if (!this.back)
  90205. this.back = new Node();
  90206. this.back.build(back);
  90207. }
  90208. };
  90209. return Node;
  90210. }());
  90211. var CSG = /** @class */ (function () {
  90212. function CSG() {
  90213. this.polygons = new Array();
  90214. }
  90215. // Convert BABYLON.Mesh to BABYLON.CSG
  90216. CSG.FromMesh = function (mesh) {
  90217. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  90218. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  90219. if (mesh instanceof BABYLON.Mesh) {
  90220. mesh.computeWorldMatrix(true);
  90221. matrix = mesh.getWorldMatrix();
  90222. meshPosition = mesh.position.clone();
  90223. meshRotation = mesh.rotation.clone();
  90224. if (mesh.rotationQuaternion) {
  90225. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  90226. }
  90227. meshScaling = mesh.scaling.clone();
  90228. }
  90229. else {
  90230. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  90231. }
  90232. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90233. var subMeshes = mesh.subMeshes;
  90234. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  90235. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  90236. vertices = [];
  90237. for (var j = 0; j < 3; j++) {
  90238. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  90239. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  90240. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  90241. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  90242. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  90243. vertex = new Vertex(position, normal, uv);
  90244. vertices.push(vertex);
  90245. }
  90246. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  90247. // To handle the case of degenerated triangle
  90248. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  90249. if (polygon.plane)
  90250. polygons.push(polygon);
  90251. }
  90252. }
  90253. var csg = CSG.FromPolygons(polygons);
  90254. csg.matrix = matrix;
  90255. csg.position = meshPosition;
  90256. csg.rotation = meshRotation;
  90257. csg.scaling = meshScaling;
  90258. csg.rotationQuaternion = meshRotationQuaternion;
  90259. currentCSGMeshId++;
  90260. return csg;
  90261. };
  90262. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  90263. CSG.FromPolygons = function (polygons) {
  90264. var csg = new CSG();
  90265. csg.polygons = polygons;
  90266. return csg;
  90267. };
  90268. CSG.prototype.clone = function () {
  90269. var csg = new CSG();
  90270. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  90271. csg.copyTransformAttributes(this);
  90272. return csg;
  90273. };
  90274. CSG.prototype.union = function (csg) {
  90275. var a = new Node(this.clone().polygons);
  90276. var b = new Node(csg.clone().polygons);
  90277. a.clipTo(b);
  90278. b.clipTo(a);
  90279. b.invert();
  90280. b.clipTo(a);
  90281. b.invert();
  90282. a.build(b.allPolygons());
  90283. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90284. };
  90285. CSG.prototype.unionInPlace = function (csg) {
  90286. var a = new Node(this.polygons);
  90287. var b = new Node(csg.polygons);
  90288. a.clipTo(b);
  90289. b.clipTo(a);
  90290. b.invert();
  90291. b.clipTo(a);
  90292. b.invert();
  90293. a.build(b.allPolygons());
  90294. this.polygons = a.allPolygons();
  90295. };
  90296. CSG.prototype.subtract = function (csg) {
  90297. var a = new Node(this.clone().polygons);
  90298. var b = new Node(csg.clone().polygons);
  90299. a.invert();
  90300. a.clipTo(b);
  90301. b.clipTo(a);
  90302. b.invert();
  90303. b.clipTo(a);
  90304. b.invert();
  90305. a.build(b.allPolygons());
  90306. a.invert();
  90307. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90308. };
  90309. CSG.prototype.subtractInPlace = function (csg) {
  90310. var a = new Node(this.polygons);
  90311. var b = new Node(csg.polygons);
  90312. a.invert();
  90313. a.clipTo(b);
  90314. b.clipTo(a);
  90315. b.invert();
  90316. b.clipTo(a);
  90317. b.invert();
  90318. a.build(b.allPolygons());
  90319. a.invert();
  90320. this.polygons = a.allPolygons();
  90321. };
  90322. CSG.prototype.intersect = function (csg) {
  90323. var a = new Node(this.clone().polygons);
  90324. var b = new Node(csg.clone().polygons);
  90325. a.invert();
  90326. b.clipTo(a);
  90327. b.invert();
  90328. a.clipTo(b);
  90329. b.clipTo(a);
  90330. a.build(b.allPolygons());
  90331. a.invert();
  90332. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  90333. };
  90334. CSG.prototype.intersectInPlace = function (csg) {
  90335. var a = new Node(this.polygons);
  90336. var b = new Node(csg.polygons);
  90337. a.invert();
  90338. b.clipTo(a);
  90339. b.invert();
  90340. a.clipTo(b);
  90341. b.clipTo(a);
  90342. a.build(b.allPolygons());
  90343. a.invert();
  90344. this.polygons = a.allPolygons();
  90345. };
  90346. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  90347. // not modified.
  90348. CSG.prototype.inverse = function () {
  90349. var csg = this.clone();
  90350. csg.inverseInPlace();
  90351. return csg;
  90352. };
  90353. CSG.prototype.inverseInPlace = function () {
  90354. this.polygons.map(function (p) { p.flip(); });
  90355. };
  90356. // This is used to keep meshes transformations so they can be restored
  90357. // when we build back a Babylon Mesh
  90358. // NB : All CSG operations are performed in world coordinates
  90359. CSG.prototype.copyTransformAttributes = function (csg) {
  90360. this.matrix = csg.matrix;
  90361. this.position = csg.position;
  90362. this.rotation = csg.rotation;
  90363. this.scaling = csg.scaling;
  90364. this.rotationQuaternion = csg.rotationQuaternion;
  90365. return this;
  90366. };
  90367. // Build Raw mesh from CSG
  90368. // Coordinates here are in world space
  90369. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  90370. var matrix = this.matrix.clone();
  90371. matrix.invert();
  90372. 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;
  90373. if (keepSubMeshes) {
  90374. // Sort Polygons, since subMeshes are indices range
  90375. polygons.sort(function (a, b) {
  90376. if (a.shared.meshId === b.shared.meshId) {
  90377. return a.shared.subMeshId - b.shared.subMeshId;
  90378. }
  90379. else {
  90380. return a.shared.meshId - b.shared.meshId;
  90381. }
  90382. });
  90383. }
  90384. for (var i = 0, il = polygons.length; i < il; i++) {
  90385. polygon = polygons[i];
  90386. // Building SubMeshes
  90387. if (!subMesh_dict[polygon.shared.meshId]) {
  90388. subMesh_dict[polygon.shared.meshId] = {};
  90389. }
  90390. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  90391. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  90392. indexStart: +Infinity,
  90393. indexEnd: -Infinity,
  90394. materialIndex: polygon.shared.materialIndex
  90395. };
  90396. }
  90397. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  90398. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  90399. polygonIndices[0] = 0;
  90400. polygonIndices[1] = j - 1;
  90401. polygonIndices[2] = j;
  90402. for (var k = 0; k < 3; k++) {
  90403. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  90404. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  90405. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  90406. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  90407. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  90408. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  90409. // Check if 2 points can be merged
  90410. if (!(typeof vertex_idx !== 'undefined' &&
  90411. normals[vertex_idx * 3] === localNormal.x &&
  90412. normals[vertex_idx * 3 + 1] === localNormal.y &&
  90413. normals[vertex_idx * 3 + 2] === localNormal.z &&
  90414. uvs[vertex_idx * 2] === uv.x &&
  90415. uvs[vertex_idx * 2 + 1] === uv.y)) {
  90416. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  90417. uvs.push(uv.x, uv.y);
  90418. normals.push(normal.x, normal.y, normal.z);
  90419. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  90420. }
  90421. indices.push(vertex_idx);
  90422. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  90423. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  90424. currentIndex++;
  90425. }
  90426. }
  90427. }
  90428. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  90429. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  90430. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  90431. mesh.setIndices(indices, null);
  90432. if (keepSubMeshes) {
  90433. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  90434. var materialIndexOffset = 0, materialMaxIndex;
  90435. mesh.subMeshes = new Array();
  90436. for (var m in subMesh_dict) {
  90437. materialMaxIndex = -1;
  90438. for (var sm in subMesh_dict[m]) {
  90439. subMesh_obj = subMesh_dict[m][sm];
  90440. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  90441. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  90442. }
  90443. materialIndexOffset += ++materialMaxIndex;
  90444. }
  90445. }
  90446. return mesh;
  90447. };
  90448. // Build Mesh from CSG taking material and transforms into account
  90449. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  90450. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  90451. mesh.material = material;
  90452. mesh.position.copyFrom(this.position);
  90453. mesh.rotation.copyFrom(this.rotation);
  90454. if (this.rotationQuaternion) {
  90455. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  90456. }
  90457. mesh.scaling.copyFrom(this.scaling);
  90458. mesh.computeWorldMatrix(true);
  90459. return mesh;
  90460. };
  90461. return CSG;
  90462. }());
  90463. BABYLON.CSG = CSG;
  90464. })(BABYLON || (BABYLON = {}));
  90465. //# sourceMappingURL=babylon.csg.js.map
  90466. var BABYLON;
  90467. (function (BABYLON) {
  90468. /**
  90469. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90470. * It controls one of the indiviual texture used in the effect.
  90471. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90472. */
  90473. var LensFlare = /** @class */ (function () {
  90474. /**
  90475. * Instantiates a new Lens Flare.
  90476. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90477. * It controls one of the indiviual texture used in the effect.
  90478. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90479. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  90480. * @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.
  90481. * @param color Define the lens color
  90482. * @param imgUrl Define the lens texture url
  90483. * @param system Define the `lensFlareSystem` this flare is part of
  90484. */
  90485. function LensFlare(
  90486. /**
  90487. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  90488. */
  90489. size,
  90490. /**
  90491. * 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.
  90492. */
  90493. position, color, imgUrl, system) {
  90494. this.size = size;
  90495. this.position = position;
  90496. /**
  90497. * Define the alpha mode to render this particular lens.
  90498. */
  90499. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90500. this.color = color || new BABYLON.Color3(1, 1, 1);
  90501. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  90502. this._system = system;
  90503. system.lensFlares.push(this);
  90504. }
  90505. /**
  90506. * Creates a new Lens Flare.
  90507. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  90508. * It controls one of the indiviual texture used in the effect.
  90509. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90510. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  90511. * @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.
  90512. * @param color Define the lens color
  90513. * @param imgUrl Define the lens texture url
  90514. * @param system Define the `lensFlareSystem` this flare is part of
  90515. * @returns The newly created Lens Flare
  90516. */
  90517. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  90518. return new LensFlare(size, position, color, imgUrl, system);
  90519. };
  90520. /**
  90521. * Dispose and release the lens flare with its associated resources.
  90522. */
  90523. LensFlare.prototype.dispose = function () {
  90524. if (this.texture) {
  90525. this.texture.dispose();
  90526. }
  90527. // Remove from scene
  90528. var index = this._system.lensFlares.indexOf(this);
  90529. this._system.lensFlares.splice(index, 1);
  90530. };
  90531. ;
  90532. return LensFlare;
  90533. }());
  90534. BABYLON.LensFlare = LensFlare;
  90535. })(BABYLON || (BABYLON = {}));
  90536. //# sourceMappingURL=babylon.lensFlare.js.map
  90537. var BABYLON;
  90538. (function (BABYLON) {
  90539. // Adds the parser to the scene parsers.
  90540. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  90541. // Lens flares
  90542. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  90543. if (!container.lensFlareSystems) {
  90544. container.lensFlareSystems = new Array();
  90545. }
  90546. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  90547. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  90548. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  90549. container.lensFlareSystems.push(lf);
  90550. }
  90551. }
  90552. });
  90553. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  90554. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90555. if (this.lensFlareSystems[index].name === name) {
  90556. return this.lensFlareSystems[index];
  90557. }
  90558. }
  90559. return null;
  90560. };
  90561. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  90562. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  90563. if (this.lensFlareSystems[index].id === id) {
  90564. return this.lensFlareSystems[index];
  90565. }
  90566. }
  90567. return null;
  90568. };
  90569. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  90570. var index = this.lensFlareSystems.indexOf(toRemove);
  90571. if (index !== -1) {
  90572. this.lensFlareSystems.splice(index, 1);
  90573. }
  90574. return index;
  90575. };
  90576. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  90577. this.lensFlareSystems.push(newLensFlareSystem);
  90578. };
  90579. /**
  90580. * Defines the lens flare scene component responsible to manage any lens flares
  90581. * in a given scene.
  90582. */
  90583. var LensFlareSystemSceneComponent = /** @class */ (function () {
  90584. /**
  90585. * Creates a new instance of the component for the given scene
  90586. * @param scene Defines the scene to register the component in
  90587. */
  90588. function LensFlareSystemSceneComponent(scene) {
  90589. /**
  90590. * The component name helpfull to identify the component in the list of scene components.
  90591. */
  90592. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  90593. this.scene = scene;
  90594. scene.lensFlareSystems = new Array();
  90595. }
  90596. /**
  90597. * Registers the component in a given scene
  90598. */
  90599. LensFlareSystemSceneComponent.prototype.register = function () {
  90600. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  90601. };
  90602. /**
  90603. * Rebuilds the elements related to this component in case of
  90604. * context lost for instance.
  90605. */
  90606. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  90607. // Nothing to do for lens flare
  90608. };
  90609. /**
  90610. * Adds all the element from the container to the scene
  90611. * @param container the container holding the elements
  90612. */
  90613. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  90614. var _this = this;
  90615. if (!container.lensFlareSystems) {
  90616. return;
  90617. }
  90618. container.lensFlareSystems.forEach(function (o) {
  90619. _this.scene.addLensFlareSystem(o);
  90620. });
  90621. };
  90622. /**
  90623. * Removes all the elements in the container from the scene
  90624. * @param container contains the elements to remove
  90625. */
  90626. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  90627. var _this = this;
  90628. if (!container.lensFlareSystems) {
  90629. return;
  90630. }
  90631. container.lensFlareSystems.forEach(function (o) {
  90632. _this.scene.removeLensFlareSystem(o);
  90633. });
  90634. };
  90635. /**
  90636. * Serializes the component data to the specified json object
  90637. * @param serializationObject The object to serialize to
  90638. */
  90639. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  90640. // Lens flares
  90641. serializationObject.lensFlareSystems = [];
  90642. var lensFlareSystems = this.scene.lensFlareSystems;
  90643. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  90644. var lensFlareSystem = lensFlareSystems_1[_i];
  90645. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  90646. }
  90647. };
  90648. /**
  90649. * Disposes the component and the associated ressources.
  90650. */
  90651. LensFlareSystemSceneComponent.prototype.dispose = function () {
  90652. var lensFlareSystems = this.scene.lensFlareSystems;
  90653. while (lensFlareSystems.length) {
  90654. lensFlareSystems[0].dispose();
  90655. }
  90656. };
  90657. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  90658. // Lens flares
  90659. if (this.scene.lensFlaresEnabled) {
  90660. var lensFlareSystems = this.scene.lensFlareSystems;
  90661. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90662. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  90663. var lensFlareSystem = lensFlareSystems_2[_i];
  90664. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  90665. lensFlareSystem.render();
  90666. }
  90667. }
  90668. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  90669. }
  90670. };
  90671. return LensFlareSystemSceneComponent;
  90672. }());
  90673. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  90674. })(BABYLON || (BABYLON = {}));
  90675. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  90676. var BABYLON;
  90677. (function (BABYLON) {
  90678. /**
  90679. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90680. * It is usually composed of several `BABYLON.lensFlare`.
  90681. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90682. */
  90683. var LensFlareSystem = /** @class */ (function () {
  90684. /**
  90685. * Instantiates a lens flare system.
  90686. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  90687. * It is usually composed of several `BABYLON.lensFlare`.
  90688. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  90689. * @param name Define the name of the lens flare system in the scene
  90690. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  90691. * @param scene Define the scene the lens flare system belongs to
  90692. */
  90693. function LensFlareSystem(
  90694. /**
  90695. * Define the name of the lens flare system
  90696. */
  90697. name, emitter, scene) {
  90698. this.name = name;
  90699. /**
  90700. * List of lens flares used in this system.
  90701. */
  90702. this.lensFlares = new Array();
  90703. /**
  90704. * Define a limit from the border the lens flare can be visible.
  90705. */
  90706. this.borderLimit = 300;
  90707. /**
  90708. * Define a viewport border we do not want to see the lens flare in.
  90709. */
  90710. this.viewportBorder = 0;
  90711. /**
  90712. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  90713. */
  90714. this.layerMask = 0x0FFFFFFF;
  90715. this._vertexBuffers = {};
  90716. this._isEnabled = true;
  90717. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90718. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  90719. if (!component) {
  90720. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  90721. scene._addComponent(component);
  90722. }
  90723. this._emitter = emitter;
  90724. this.id = name;
  90725. scene.lensFlareSystems.push(this);
  90726. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  90727. var engine = scene.getEngine();
  90728. // VBO
  90729. var vertices = [];
  90730. vertices.push(1, 1);
  90731. vertices.push(-1, 1);
  90732. vertices.push(-1, -1);
  90733. vertices.push(1, -1);
  90734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90735. // Indices
  90736. var indices = [];
  90737. indices.push(0);
  90738. indices.push(1);
  90739. indices.push(2);
  90740. indices.push(0);
  90741. indices.push(2);
  90742. indices.push(3);
  90743. this._indexBuffer = engine.createIndexBuffer(indices);
  90744. // Effects
  90745. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  90746. }
  90747. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  90748. /**
  90749. * Define if the lens flare system is enabled.
  90750. */
  90751. get: function () {
  90752. return this._isEnabled;
  90753. },
  90754. set: function (value) {
  90755. this._isEnabled = value;
  90756. },
  90757. enumerable: true,
  90758. configurable: true
  90759. });
  90760. /**
  90761. * Get the scene the effects belongs to.
  90762. * @returns the scene holding the lens flare system
  90763. */
  90764. LensFlareSystem.prototype.getScene = function () {
  90765. return this._scene;
  90766. };
  90767. /**
  90768. * Get the emitter of the lens flare system.
  90769. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90770. * @returns the emitter of the lens flare system
  90771. */
  90772. LensFlareSystem.prototype.getEmitter = function () {
  90773. return this._emitter;
  90774. };
  90775. /**
  90776. * Set the emitter of the lens flare system.
  90777. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  90778. * @param newEmitter Define the new emitter of the system
  90779. */
  90780. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  90781. this._emitter = newEmitter;
  90782. };
  90783. /**
  90784. * Get the lens flare system emitter position.
  90785. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  90786. * @returns the position
  90787. */
  90788. LensFlareSystem.prototype.getEmitterPosition = function () {
  90789. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  90790. };
  90791. /**
  90792. * @hidden
  90793. */
  90794. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  90795. var position = this.getEmitterPosition();
  90796. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  90797. this._positionX = position.x;
  90798. this._positionY = position.y;
  90799. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  90800. if (this.viewportBorder > 0) {
  90801. globalViewport.x -= this.viewportBorder;
  90802. globalViewport.y -= this.viewportBorder;
  90803. globalViewport.width += this.viewportBorder * 2;
  90804. globalViewport.height += this.viewportBorder * 2;
  90805. position.x += this.viewportBorder;
  90806. position.y += this.viewportBorder;
  90807. this._positionX += this.viewportBorder;
  90808. this._positionY += this.viewportBorder;
  90809. }
  90810. if (position.z > 0) {
  90811. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  90812. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  90813. return true;
  90814. }
  90815. return true;
  90816. }
  90817. return false;
  90818. };
  90819. /** @hidden */
  90820. LensFlareSystem.prototype._isVisible = function () {
  90821. if (!this._isEnabled || !this._scene.activeCamera) {
  90822. return false;
  90823. }
  90824. var emitterPosition = this.getEmitterPosition();
  90825. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  90826. var distance = direction.length();
  90827. direction.normalize();
  90828. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  90829. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  90830. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  90831. };
  90832. /**
  90833. * @hidden
  90834. */
  90835. LensFlareSystem.prototype.render = function () {
  90836. if (!this._effect.isReady() || !this._scene.activeCamera)
  90837. return false;
  90838. var engine = this._scene.getEngine();
  90839. var viewport = this._scene.activeCamera.viewport;
  90840. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  90841. // Position
  90842. if (!this.computeEffectivePosition(globalViewport)) {
  90843. return false;
  90844. }
  90845. // Visibility
  90846. if (!this._isVisible()) {
  90847. return false;
  90848. }
  90849. // Intensity
  90850. var awayX;
  90851. var awayY;
  90852. if (this._positionX < this.borderLimit + globalViewport.x) {
  90853. awayX = this.borderLimit + globalViewport.x - this._positionX;
  90854. }
  90855. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  90856. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  90857. }
  90858. else {
  90859. awayX = 0;
  90860. }
  90861. if (this._positionY < this.borderLimit + globalViewport.y) {
  90862. awayY = this.borderLimit + globalViewport.y - this._positionY;
  90863. }
  90864. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  90865. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  90866. }
  90867. else {
  90868. awayY = 0;
  90869. }
  90870. var away = (awayX > awayY) ? awayX : awayY;
  90871. away -= this.viewportBorder;
  90872. if (away > this.borderLimit) {
  90873. away = this.borderLimit;
  90874. }
  90875. var intensity = 1.0 - (away / this.borderLimit);
  90876. if (intensity < 0) {
  90877. return false;
  90878. }
  90879. if (intensity > 1.0) {
  90880. intensity = 1.0;
  90881. }
  90882. if (this.viewportBorder > 0) {
  90883. globalViewport.x += this.viewportBorder;
  90884. globalViewport.y += this.viewportBorder;
  90885. globalViewport.width -= this.viewportBorder * 2;
  90886. globalViewport.height -= this.viewportBorder * 2;
  90887. this._positionX -= this.viewportBorder;
  90888. this._positionY -= this.viewportBorder;
  90889. }
  90890. // Position
  90891. var centerX = globalViewport.x + globalViewport.width / 2;
  90892. var centerY = globalViewport.y + globalViewport.height / 2;
  90893. var distX = centerX - this._positionX;
  90894. var distY = centerY - this._positionY;
  90895. // Effects
  90896. engine.enableEffect(this._effect);
  90897. engine.setState(false);
  90898. engine.setDepthBuffer(false);
  90899. // VBOs
  90900. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  90901. // Flares
  90902. for (var index = 0; index < this.lensFlares.length; index++) {
  90903. var flare = this.lensFlares[index];
  90904. engine.setAlphaMode(flare.alphaMode);
  90905. var x = centerX - (distX * flare.position);
  90906. var y = centerY - (distY * flare.position);
  90907. var cw = flare.size;
  90908. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  90909. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  90910. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  90911. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  90912. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  90913. // Texture
  90914. this._effect.setTexture("textureSampler", flare.texture);
  90915. // Color
  90916. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  90917. // Draw order
  90918. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90919. }
  90920. engine.setDepthBuffer(true);
  90921. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  90922. return true;
  90923. };
  90924. /**
  90925. * Dispose and release the lens flare with its associated resources.
  90926. */
  90927. LensFlareSystem.prototype.dispose = function () {
  90928. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90929. if (vertexBuffer) {
  90930. vertexBuffer.dispose();
  90931. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90932. }
  90933. if (this._indexBuffer) {
  90934. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90935. this._indexBuffer = null;
  90936. }
  90937. while (this.lensFlares.length) {
  90938. this.lensFlares[0].dispose();
  90939. }
  90940. // Remove from scene
  90941. var index = this._scene.lensFlareSystems.indexOf(this);
  90942. this._scene.lensFlareSystems.splice(index, 1);
  90943. };
  90944. /**
  90945. * Parse a lens flare system from a JSON repressentation
  90946. * @param parsedLensFlareSystem Define the JSON to parse
  90947. * @param scene Define the scene the parsed system should be instantiated in
  90948. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  90949. * @returns the parsed system
  90950. */
  90951. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  90952. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  90953. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  90954. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  90955. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  90956. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  90957. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  90958. var parsedFlare = parsedLensFlareSystem.flares[index];
  90959. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  90960. }
  90961. return lensFlareSystem;
  90962. };
  90963. /**
  90964. * Serialize the current Lens Flare System into a JSON representation.
  90965. * @returns the serialized JSON
  90966. */
  90967. LensFlareSystem.prototype.serialize = function () {
  90968. var serializationObject = {};
  90969. serializationObject.id = this.id;
  90970. serializationObject.name = this.name;
  90971. serializationObject.emitterId = this.getEmitter().id;
  90972. serializationObject.borderLimit = this.borderLimit;
  90973. serializationObject.flares = [];
  90974. for (var index = 0; index < this.lensFlares.length; index++) {
  90975. var flare = this.lensFlares[index];
  90976. serializationObject.flares.push({
  90977. size: flare.size,
  90978. position: flare.position,
  90979. color: flare.color.asArray(),
  90980. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  90981. });
  90982. }
  90983. return serializationObject;
  90984. };
  90985. return LensFlareSystem;
  90986. }());
  90987. BABYLON.LensFlareSystem = LensFlareSystem;
  90988. })(BABYLON || (BABYLON = {}));
  90989. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  90990. var BABYLON;
  90991. (function (BABYLON) {
  90992. /**
  90993. * This is a holder class for the physics joint created by the physics plugin.
  90994. * It holds a set of functions to control the underlying joint.
  90995. */
  90996. var PhysicsJoint = /** @class */ (function () {
  90997. function PhysicsJoint(type, jointData) {
  90998. this.type = type;
  90999. this.jointData = jointData;
  91000. jointData.nativeParams = jointData.nativeParams || {};
  91001. }
  91002. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  91003. get: function () {
  91004. return this._physicsJoint;
  91005. },
  91006. set: function (newJoint) {
  91007. if (this._physicsJoint) {
  91008. //remove from the wolrd
  91009. }
  91010. this._physicsJoint = newJoint;
  91011. },
  91012. enumerable: true,
  91013. configurable: true
  91014. });
  91015. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  91016. set: function (physicsPlugin) {
  91017. this._physicsPlugin = physicsPlugin;
  91018. },
  91019. enumerable: true,
  91020. configurable: true
  91021. });
  91022. /**
  91023. * Execute a function that is physics-plugin specific.
  91024. * @param {Function} func the function that will be executed.
  91025. * It accepts two parameters: the physics world and the physics joint.
  91026. */
  91027. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  91028. func(this._physicsPlugin.world, this._physicsJoint);
  91029. };
  91030. //TODO check if the native joints are the same
  91031. //Joint Types
  91032. PhysicsJoint.DistanceJoint = 0;
  91033. PhysicsJoint.HingeJoint = 1;
  91034. PhysicsJoint.BallAndSocketJoint = 2;
  91035. PhysicsJoint.WheelJoint = 3;
  91036. PhysicsJoint.SliderJoint = 4;
  91037. //OIMO
  91038. PhysicsJoint.PrismaticJoint = 5;
  91039. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  91040. PhysicsJoint.UniversalJoint = 6;
  91041. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  91042. //Cannon
  91043. //Similar to a Ball-Joint. Different in params
  91044. PhysicsJoint.PointToPointJoint = 8;
  91045. //Cannon only at the moment
  91046. PhysicsJoint.SpringJoint = 9;
  91047. PhysicsJoint.LockJoint = 10;
  91048. return PhysicsJoint;
  91049. }());
  91050. BABYLON.PhysicsJoint = PhysicsJoint;
  91051. /**
  91052. * A class representing a physics distance joint.
  91053. */
  91054. var DistanceJoint = /** @class */ (function (_super) {
  91055. __extends(DistanceJoint, _super);
  91056. function DistanceJoint(jointData) {
  91057. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  91058. }
  91059. /**
  91060. * Update the predefined distance.
  91061. */
  91062. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  91063. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  91064. };
  91065. return DistanceJoint;
  91066. }(PhysicsJoint));
  91067. BABYLON.DistanceJoint = DistanceJoint;
  91068. var MotorEnabledJoint = /** @class */ (function (_super) {
  91069. __extends(MotorEnabledJoint, _super);
  91070. function MotorEnabledJoint(type, jointData) {
  91071. return _super.call(this, type, jointData) || this;
  91072. }
  91073. /**
  91074. * Set the motor values.
  91075. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91076. * @param {number} force the force to apply
  91077. * @param {number} maxForce max force for this motor.
  91078. */
  91079. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  91080. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91081. };
  91082. /**
  91083. * Set the motor's limits.
  91084. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91085. */
  91086. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91087. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91088. };
  91089. return MotorEnabledJoint;
  91090. }(PhysicsJoint));
  91091. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  91092. /**
  91093. * This class represents a single hinge physics joint
  91094. */
  91095. var HingeJoint = /** @class */ (function (_super) {
  91096. __extends(HingeJoint, _super);
  91097. function HingeJoint(jointData) {
  91098. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  91099. }
  91100. /**
  91101. * Set the motor values.
  91102. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91103. * @param {number} force the force to apply
  91104. * @param {number} maxForce max force for this motor.
  91105. */
  91106. HingeJoint.prototype.setMotor = function (force, maxForce) {
  91107. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  91108. };
  91109. /**
  91110. * Set the motor's limits.
  91111. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91112. */
  91113. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  91114. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  91115. };
  91116. return HingeJoint;
  91117. }(MotorEnabledJoint));
  91118. BABYLON.HingeJoint = HingeJoint;
  91119. /**
  91120. * This class represents a dual hinge physics joint (same as wheel joint)
  91121. */
  91122. var Hinge2Joint = /** @class */ (function (_super) {
  91123. __extends(Hinge2Joint, _super);
  91124. function Hinge2Joint(jointData) {
  91125. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  91126. }
  91127. /**
  91128. * Set the motor values.
  91129. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91130. * @param {number} force the force to apply
  91131. * @param {number} maxForce max force for this motor.
  91132. * @param {motorIndex} the motor's index, 0 or 1.
  91133. */
  91134. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  91135. if (motorIndex === void 0) { motorIndex = 0; }
  91136. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  91137. };
  91138. /**
  91139. * Set the motor limits.
  91140. * Attention, this function is plugin specific. Engines won't react 100% the same.
  91141. * @param {number} upperLimit the upper limit
  91142. * @param {number} lowerLimit lower limit
  91143. * @param {motorIndex} the motor's index, 0 or 1.
  91144. */
  91145. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  91146. if (motorIndex === void 0) { motorIndex = 0; }
  91147. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  91148. };
  91149. return Hinge2Joint;
  91150. }(MotorEnabledJoint));
  91151. BABYLON.Hinge2Joint = Hinge2Joint;
  91152. })(BABYLON || (BABYLON = {}));
  91153. //# sourceMappingURL=babylon.physicsJoint.js.map
  91154. var BABYLON;
  91155. (function (BABYLON) {
  91156. var PhysicsImpostor = /** @class */ (function () {
  91157. function PhysicsImpostor(object, type, _options, _scene) {
  91158. if (_options === void 0) { _options = { mass: 0 }; }
  91159. var _this = this;
  91160. this.object = object;
  91161. this.type = type;
  91162. this._options = _options;
  91163. this._scene = _scene;
  91164. this._bodyUpdateRequired = false;
  91165. this._onBeforePhysicsStepCallbacks = new Array();
  91166. this._onAfterPhysicsStepCallbacks = new Array();
  91167. this._onPhysicsCollideCallbacks = [];
  91168. this._deltaPosition = BABYLON.Vector3.Zero();
  91169. this._isDisposed = false;
  91170. //temp variables for parent rotation calculations
  91171. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  91172. this._tmpQuat = new BABYLON.Quaternion();
  91173. this._tmpQuat2 = new BABYLON.Quaternion();
  91174. /**
  91175. * this function is executed by the physics engine.
  91176. */
  91177. this.beforeStep = function () {
  91178. if (!_this._physicsEngine) {
  91179. return;
  91180. }
  91181. _this.object.translate(_this._deltaPosition, -1);
  91182. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  91183. _this.object.computeWorldMatrix(false);
  91184. if (_this.object.parent && _this.object.rotationQuaternion) {
  91185. _this.getParentsRotation();
  91186. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  91187. }
  91188. else {
  91189. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  91190. }
  91191. if (!_this._options.disableBidirectionalTransformation) {
  91192. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  91193. }
  91194. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  91195. func(_this);
  91196. });
  91197. };
  91198. /**
  91199. * this function is executed by the physics engine.
  91200. */
  91201. this.afterStep = function () {
  91202. if (!_this._physicsEngine) {
  91203. return;
  91204. }
  91205. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  91206. func(_this);
  91207. });
  91208. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  91209. // object has now its world rotation. needs to be converted to local.
  91210. if (_this.object.parent && _this.object.rotationQuaternion) {
  91211. _this.getParentsRotation();
  91212. _this._tmpQuat.conjugateInPlace();
  91213. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  91214. }
  91215. // take the position set and make it the absolute position of this object.
  91216. _this.object.setAbsolutePosition(_this.object.position);
  91217. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  91218. _this.object.translate(_this._deltaPosition, 1);
  91219. };
  91220. /**
  91221. * Legacy collision detection event support
  91222. */
  91223. this.onCollideEvent = null;
  91224. //event and body object due to cannon's event-based architecture.
  91225. this.onCollide = function (e) {
  91226. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  91227. return;
  91228. }
  91229. if (!_this._physicsEngine) {
  91230. return;
  91231. }
  91232. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  91233. if (otherImpostor) {
  91234. // Legacy collision detection event support
  91235. if (_this.onCollideEvent) {
  91236. _this.onCollideEvent(_this, otherImpostor);
  91237. }
  91238. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  91239. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  91240. }).forEach(function (obj) {
  91241. obj.callback(_this, otherImpostor);
  91242. });
  91243. }
  91244. };
  91245. //sanity check!
  91246. if (!this.object) {
  91247. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  91248. return;
  91249. }
  91250. //legacy support for old syntax.
  91251. if (!this._scene && object.getScene) {
  91252. this._scene = object.getScene();
  91253. }
  91254. if (!this._scene) {
  91255. return;
  91256. }
  91257. this._physicsEngine = this._scene.getPhysicsEngine();
  91258. if (!this._physicsEngine) {
  91259. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  91260. }
  91261. else {
  91262. //set the object's quaternion, if not set
  91263. if (!this.object.rotationQuaternion) {
  91264. if (this.object.rotation) {
  91265. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  91266. }
  91267. else {
  91268. this.object.rotationQuaternion = new BABYLON.Quaternion();
  91269. }
  91270. }
  91271. //default options params
  91272. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  91273. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  91274. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  91275. this._joints = [];
  91276. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  91277. if (!this.object.parent || this._options.ignoreParent) {
  91278. this._init();
  91279. }
  91280. else if (this.object.parent.physicsImpostor) {
  91281. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  91282. }
  91283. }
  91284. }
  91285. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  91286. get: function () {
  91287. return this._isDisposed;
  91288. },
  91289. enumerable: true,
  91290. configurable: true
  91291. });
  91292. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  91293. get: function () {
  91294. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  91295. },
  91296. set: function (value) {
  91297. this.setMass(value);
  91298. },
  91299. enumerable: true,
  91300. configurable: true
  91301. });
  91302. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  91303. get: function () {
  91304. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  91305. },
  91306. set: function (value) {
  91307. if (!this._physicsEngine) {
  91308. return;
  91309. }
  91310. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  91311. },
  91312. enumerable: true,
  91313. configurable: true
  91314. });
  91315. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  91316. get: function () {
  91317. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  91318. },
  91319. set: function (value) {
  91320. if (!this._physicsEngine) {
  91321. return;
  91322. }
  91323. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  91324. },
  91325. enumerable: true,
  91326. configurable: true
  91327. });
  91328. /**
  91329. * This function will completly initialize this impostor.
  91330. * It will create a new body - but only if this mesh has no parent.
  91331. * If it has, this impostor will not be used other than to define the impostor
  91332. * of the child mesh.
  91333. * @hidden
  91334. */
  91335. PhysicsImpostor.prototype._init = function () {
  91336. if (!this._physicsEngine) {
  91337. return;
  91338. }
  91339. this._physicsEngine.removeImpostor(this);
  91340. this.physicsBody = null;
  91341. this._parent = this._parent || this._getPhysicsParent();
  91342. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  91343. this._physicsEngine.addImpostor(this);
  91344. }
  91345. };
  91346. PhysicsImpostor.prototype._getPhysicsParent = function () {
  91347. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  91348. var parentMesh = this.object.parent;
  91349. return parentMesh.physicsImpostor;
  91350. }
  91351. return null;
  91352. };
  91353. /**
  91354. * Should a new body be generated.
  91355. */
  91356. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  91357. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  91358. };
  91359. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  91360. this.forceUpdate();
  91361. };
  91362. /**
  91363. * Force a regeneration of this or the parent's impostor's body.
  91364. * Use under cautious - This will remove all joints already implemented.
  91365. */
  91366. PhysicsImpostor.prototype.forceUpdate = function () {
  91367. this._init();
  91368. if (this.parent && !this._options.ignoreParent) {
  91369. this.parent.forceUpdate();
  91370. }
  91371. };
  91372. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  91373. /*public get mesh(): AbstractMesh {
  91374. return this._mesh;
  91375. }*/
  91376. /**
  91377. * Gets the body that holds this impostor. Either its own, or its parent.
  91378. */
  91379. get: function () {
  91380. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  91381. },
  91382. /**
  91383. * Set the physics body. Used mainly by the physics engine/plugin
  91384. */
  91385. set: function (physicsBody) {
  91386. if (this._physicsBody && this._physicsEngine) {
  91387. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  91388. }
  91389. this._physicsBody = physicsBody;
  91390. this.resetUpdateFlags();
  91391. },
  91392. enumerable: true,
  91393. configurable: true
  91394. });
  91395. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  91396. get: function () {
  91397. return !this._options.ignoreParent && this._parent ? this._parent : null;
  91398. },
  91399. set: function (value) {
  91400. this._parent = value;
  91401. },
  91402. enumerable: true,
  91403. configurable: true
  91404. });
  91405. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  91406. this._bodyUpdateRequired = false;
  91407. };
  91408. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  91409. if (this.object.getBoundingInfo) {
  91410. var q = this.object.rotationQuaternion;
  91411. //reset rotation
  91412. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  91413. //calculate the world matrix with no rotation
  91414. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91415. var boundingInfo = this.object.getBoundingInfo();
  91416. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  91417. //bring back the rotation
  91418. this.object.rotationQuaternion = q;
  91419. //calculate the world matrix with the new rotation
  91420. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  91421. return size;
  91422. }
  91423. else {
  91424. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  91425. }
  91426. };
  91427. PhysicsImpostor.prototype.getObjectCenter = function () {
  91428. if (this.object.getBoundingInfo) {
  91429. var boundingInfo = this.object.getBoundingInfo();
  91430. return boundingInfo.boundingBox.centerWorld;
  91431. }
  91432. else {
  91433. return this.object.position;
  91434. }
  91435. };
  91436. /**
  91437. * Get a specific parametes from the options parameter.
  91438. */
  91439. PhysicsImpostor.prototype.getParam = function (paramName) {
  91440. return this._options[paramName];
  91441. };
  91442. /**
  91443. * Sets a specific parameter in the options given to the physics plugin
  91444. */
  91445. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  91446. this._options[paramName] = value;
  91447. this._bodyUpdateRequired = true;
  91448. };
  91449. /**
  91450. * Specifically change the body's mass option. Won't recreate the physics body object
  91451. */
  91452. PhysicsImpostor.prototype.setMass = function (mass) {
  91453. if (this.getParam("mass") !== mass) {
  91454. this.setParam("mass", mass);
  91455. }
  91456. if (this._physicsEngine) {
  91457. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  91458. }
  91459. };
  91460. PhysicsImpostor.prototype.getLinearVelocity = function () {
  91461. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  91462. };
  91463. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  91464. if (this._physicsEngine) {
  91465. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  91466. }
  91467. };
  91468. PhysicsImpostor.prototype.getAngularVelocity = function () {
  91469. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  91470. };
  91471. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  91472. if (this._physicsEngine) {
  91473. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  91474. }
  91475. };
  91476. /**
  91477. * Execute a function with the physics plugin native code.
  91478. * Provide a function the will have two variables - the world object and the physics body object.
  91479. */
  91480. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  91481. if (this._physicsEngine) {
  91482. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  91483. }
  91484. };
  91485. /**
  91486. * Register a function that will be executed before the physics world is stepping forward.
  91487. */
  91488. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  91489. this._onBeforePhysicsStepCallbacks.push(func);
  91490. };
  91491. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  91492. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  91493. if (index > -1) {
  91494. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  91495. }
  91496. else {
  91497. BABYLON.Tools.Warn("Function to remove was not found");
  91498. }
  91499. };
  91500. /**
  91501. * Register a function that will be executed after the physics step
  91502. */
  91503. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  91504. this._onAfterPhysicsStepCallbacks.push(func);
  91505. };
  91506. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  91507. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  91508. if (index > -1) {
  91509. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  91510. }
  91511. else {
  91512. BABYLON.Tools.Warn("Function to remove was not found");
  91513. }
  91514. };
  91515. /**
  91516. * register a function that will be executed when this impostor collides against a different body.
  91517. */
  91518. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  91519. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91520. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  91521. };
  91522. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  91523. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  91524. var index = -1;
  91525. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  91526. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  91527. // chcek the arrays match
  91528. var sameList = cbDef.otherImpostors.every(function (impostor) {
  91529. return collidedAgainstList.indexOf(impostor) > -1;
  91530. });
  91531. if (sameList) {
  91532. index = idx;
  91533. }
  91534. return sameList;
  91535. }
  91536. return false;
  91537. });
  91538. if (found) {
  91539. this._onPhysicsCollideCallbacks.splice(index, 1);
  91540. }
  91541. else {
  91542. BABYLON.Tools.Warn("Function to remove was not found");
  91543. }
  91544. };
  91545. PhysicsImpostor.prototype.getParentsRotation = function () {
  91546. var parent = this.object.parent;
  91547. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  91548. while (parent) {
  91549. if (parent.rotationQuaternion) {
  91550. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  91551. }
  91552. else {
  91553. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  91554. }
  91555. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  91556. parent = parent.parent;
  91557. }
  91558. return this._tmpQuat;
  91559. };
  91560. /**
  91561. * Apply a force
  91562. */
  91563. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  91564. if (this._physicsEngine) {
  91565. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  91566. }
  91567. return this;
  91568. };
  91569. /**
  91570. * Apply an impulse
  91571. */
  91572. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  91573. if (this._physicsEngine) {
  91574. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  91575. }
  91576. return this;
  91577. };
  91578. /**
  91579. * A help function to create a joint.
  91580. */
  91581. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  91582. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  91583. this.addJoint(otherImpostor, joint);
  91584. return this;
  91585. };
  91586. /**
  91587. * Add a joint to this impostor with a different impostor.
  91588. */
  91589. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  91590. this._joints.push({
  91591. otherImpostor: otherImpostor,
  91592. joint: joint
  91593. });
  91594. if (this._physicsEngine) {
  91595. this._physicsEngine.addJoint(this, otherImpostor, joint);
  91596. }
  91597. return this;
  91598. };
  91599. /**
  91600. * Will keep this body still, in a sleep mode.
  91601. */
  91602. PhysicsImpostor.prototype.sleep = function () {
  91603. if (this._physicsEngine) {
  91604. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  91605. }
  91606. return this;
  91607. };
  91608. /**
  91609. * Wake the body up.
  91610. */
  91611. PhysicsImpostor.prototype.wakeUp = function () {
  91612. if (this._physicsEngine) {
  91613. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  91614. }
  91615. return this;
  91616. };
  91617. PhysicsImpostor.prototype.clone = function (newObject) {
  91618. if (!newObject)
  91619. return null;
  91620. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  91621. };
  91622. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  91623. var _this = this;
  91624. //no dispose if no physics engine is available.
  91625. if (!this._physicsEngine) {
  91626. return;
  91627. }
  91628. this._joints.forEach(function (j) {
  91629. if (_this._physicsEngine) {
  91630. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  91631. }
  91632. });
  91633. //dispose the physics body
  91634. this._physicsEngine.removeImpostor(this);
  91635. if (this.parent) {
  91636. this.parent.forceUpdate();
  91637. }
  91638. else {
  91639. /*this._object.getChildMeshes().forEach(function(mesh) {
  91640. if (mesh.physicsImpostor) {
  91641. if (disposeChildren) {
  91642. mesh.physicsImpostor.dispose();
  91643. mesh.physicsImpostor = null;
  91644. }
  91645. }
  91646. })*/
  91647. }
  91648. this._isDisposed = true;
  91649. };
  91650. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  91651. this._deltaPosition.copyFrom(position);
  91652. };
  91653. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  91654. if (!this._deltaRotation) {
  91655. this._deltaRotation = new BABYLON.Quaternion();
  91656. }
  91657. this._deltaRotation.copyFrom(rotation);
  91658. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  91659. };
  91660. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  91661. if (this._physicsEngine) {
  91662. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  91663. }
  91664. return this;
  91665. };
  91666. PhysicsImpostor.prototype.getRadius = function () {
  91667. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  91668. };
  91669. /**
  91670. * Sync a bone with this impostor
  91671. * @param bone The bone to sync to the impostor.
  91672. * @param boneMesh The mesh that the bone is influencing.
  91673. * @param jointPivot The pivot of the joint / bone in local space.
  91674. * @param distToJoint Optional distance from the impostor to the joint.
  91675. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91676. */
  91677. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  91678. var tempVec = PhysicsImpostor._tmpVecs[0];
  91679. var mesh = this.object;
  91680. if (mesh.rotationQuaternion) {
  91681. if (adjustRotation) {
  91682. var tempQuat = PhysicsImpostor._tmpQuat;
  91683. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  91684. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  91685. }
  91686. else {
  91687. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  91688. }
  91689. }
  91690. tempVec.x = 0;
  91691. tempVec.y = 0;
  91692. tempVec.z = 0;
  91693. if (jointPivot) {
  91694. tempVec.x = jointPivot.x;
  91695. tempVec.y = jointPivot.y;
  91696. tempVec.z = jointPivot.z;
  91697. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  91698. if (distToJoint === undefined || distToJoint === null) {
  91699. distToJoint = jointPivot.length();
  91700. }
  91701. tempVec.x *= distToJoint;
  91702. tempVec.y *= distToJoint;
  91703. tempVec.z *= distToJoint;
  91704. }
  91705. if (bone.getParent()) {
  91706. tempVec.addInPlace(mesh.getAbsolutePosition());
  91707. bone.setAbsolutePosition(tempVec, boneMesh);
  91708. }
  91709. else {
  91710. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  91711. boneMesh.position.x -= tempVec.x;
  91712. boneMesh.position.y -= tempVec.y;
  91713. boneMesh.position.z -= tempVec.z;
  91714. }
  91715. };
  91716. /**
  91717. * Sync impostor to a bone
  91718. * @param bone The bone that the impostor will be synced to.
  91719. * @param boneMesh The mesh that the bone is influencing.
  91720. * @param jointPivot The pivot of the joint / bone in local space.
  91721. * @param distToJoint Optional distance from the impostor to the joint.
  91722. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  91723. * @param boneAxis Optional vector3 axis the bone is aligned with
  91724. */
  91725. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  91726. var mesh = this.object;
  91727. if (mesh.rotationQuaternion) {
  91728. if (adjustRotation) {
  91729. var tempQuat = PhysicsImpostor._tmpQuat;
  91730. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  91731. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  91732. }
  91733. else {
  91734. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  91735. }
  91736. }
  91737. var pos = PhysicsImpostor._tmpVecs[0];
  91738. var boneDir = PhysicsImpostor._tmpVecs[1];
  91739. if (!boneAxis) {
  91740. boneAxis = PhysicsImpostor._tmpVecs[2];
  91741. boneAxis.x = 0;
  91742. boneAxis.y = 1;
  91743. boneAxis.z = 0;
  91744. }
  91745. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  91746. bone.getAbsolutePositionToRef(boneMesh, pos);
  91747. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  91748. distToJoint = jointPivot.length();
  91749. }
  91750. if (distToJoint !== undefined && distToJoint !== null) {
  91751. pos.x += boneDir.x * distToJoint;
  91752. pos.y += boneDir.y * distToJoint;
  91753. pos.z += boneDir.z * distToJoint;
  91754. }
  91755. mesh.setAbsolutePosition(pos);
  91756. };
  91757. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  91758. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  91759. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91760. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  91761. //Impostor types
  91762. PhysicsImpostor.NoImpostor = 0;
  91763. PhysicsImpostor.SphereImpostor = 1;
  91764. PhysicsImpostor.BoxImpostor = 2;
  91765. PhysicsImpostor.PlaneImpostor = 3;
  91766. PhysicsImpostor.MeshImpostor = 4;
  91767. PhysicsImpostor.CylinderImpostor = 7;
  91768. PhysicsImpostor.ParticleImpostor = 8;
  91769. PhysicsImpostor.HeightmapImpostor = 9;
  91770. return PhysicsImpostor;
  91771. }());
  91772. BABYLON.PhysicsImpostor = PhysicsImpostor;
  91773. })(BABYLON || (BABYLON = {}));
  91774. //# sourceMappingURL=babylon.physicsImpostor.js.map
  91775. var BABYLON;
  91776. (function (BABYLON) {
  91777. /**
  91778. * Class used to control physics engine
  91779. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  91780. */
  91781. var PhysicsEngine = /** @class */ (function () {
  91782. /**
  91783. * Creates a new Physics Engine
  91784. * @param gravity defines the gravity vector used by the simulation
  91785. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  91786. */
  91787. function PhysicsEngine(gravity, _physicsPlugin) {
  91788. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  91789. this._physicsPlugin = _physicsPlugin;
  91790. this._impostors = [];
  91791. this._joints = [];
  91792. if (!this._physicsPlugin.isSupported()) {
  91793. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  91794. + "Please make sure it is included.");
  91795. }
  91796. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  91797. this.setGravity(gravity);
  91798. this.setTimeStep();
  91799. }
  91800. /**
  91801. * Sets the gravity vector used by the simulation
  91802. * @param gravity defines the gravity vector to use
  91803. */
  91804. PhysicsEngine.prototype.setGravity = function (gravity) {
  91805. this.gravity = gravity;
  91806. this._physicsPlugin.setGravity(this.gravity);
  91807. };
  91808. /**
  91809. * Set the time step of the physics engine.
  91810. * Default is 1/60.
  91811. * To slow it down, enter 1/600 for example.
  91812. * To speed it up, 1/30
  91813. * @param newTimeStep defines the new timestep to apply to this world.
  91814. */
  91815. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  91816. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  91817. this._physicsPlugin.setTimeStep(newTimeStep);
  91818. };
  91819. /**
  91820. * Get the time step of the physics engine.
  91821. * @returns the current time step
  91822. */
  91823. PhysicsEngine.prototype.getTimeStep = function () {
  91824. return this._physicsPlugin.getTimeStep();
  91825. };
  91826. /**
  91827. * Release all resources
  91828. */
  91829. PhysicsEngine.prototype.dispose = function () {
  91830. this._impostors.forEach(function (impostor) {
  91831. impostor.dispose();
  91832. });
  91833. this._physicsPlugin.dispose();
  91834. };
  91835. /**
  91836. * Gets the name of the current physics plugin
  91837. * @returns the name of the plugin
  91838. */
  91839. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  91840. return this._physicsPlugin.name;
  91841. };
  91842. /**
  91843. * Adding a new impostor for the impostor tracking.
  91844. * This will be done by the impostor itself.
  91845. * @param impostor the impostor to add
  91846. */
  91847. PhysicsEngine.prototype.addImpostor = function (impostor) {
  91848. impostor.uniqueId = this._impostors.push(impostor);
  91849. //if no parent, generate the body
  91850. if (!impostor.parent) {
  91851. this._physicsPlugin.generatePhysicsBody(impostor);
  91852. }
  91853. };
  91854. /**
  91855. * Remove an impostor from the engine.
  91856. * This impostor and its mesh will not longer be updated by the physics engine.
  91857. * @param impostor the impostor to remove
  91858. */
  91859. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  91860. var index = this._impostors.indexOf(impostor);
  91861. if (index > -1) {
  91862. var removed = this._impostors.splice(index, 1);
  91863. //Is it needed?
  91864. if (removed.length) {
  91865. //this will also remove it from the world.
  91866. removed[0].physicsBody = null;
  91867. }
  91868. }
  91869. };
  91870. /**
  91871. * Add a joint to the physics engine
  91872. * @param mainImpostor defines the main impostor to which the joint is added.
  91873. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  91874. * @param joint defines the joint that will connect both impostors.
  91875. */
  91876. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  91877. var impostorJoint = {
  91878. mainImpostor: mainImpostor,
  91879. connectedImpostor: connectedImpostor,
  91880. joint: joint
  91881. };
  91882. joint.physicsPlugin = this._physicsPlugin;
  91883. this._joints.push(impostorJoint);
  91884. this._physicsPlugin.generateJoint(impostorJoint);
  91885. };
  91886. /**
  91887. * Removes a joint from the simulation
  91888. * @param mainImpostor defines the impostor used with the joint
  91889. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  91890. * @param joint defines the joint to remove
  91891. */
  91892. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  91893. var matchingJoints = this._joints.filter(function (impostorJoint) {
  91894. return (impostorJoint.connectedImpostor === connectedImpostor
  91895. && impostorJoint.joint === joint
  91896. && impostorJoint.mainImpostor === mainImpostor);
  91897. });
  91898. if (matchingJoints.length) {
  91899. this._physicsPlugin.removeJoint(matchingJoints[0]);
  91900. //TODO remove it from the list as well
  91901. }
  91902. };
  91903. /**
  91904. * Called by the scene. No need to call it.
  91905. * @param delta defines the timespam between frames
  91906. */
  91907. PhysicsEngine.prototype._step = function (delta) {
  91908. var _this = this;
  91909. //check if any mesh has no body / requires an update
  91910. this._impostors.forEach(function (impostor) {
  91911. if (impostor.isBodyInitRequired()) {
  91912. _this._physicsPlugin.generatePhysicsBody(impostor);
  91913. }
  91914. });
  91915. if (delta > 0.1) {
  91916. delta = 0.1;
  91917. }
  91918. else if (delta <= 0) {
  91919. delta = 1.0 / 60.0;
  91920. }
  91921. this._physicsPlugin.executeStep(delta, this._impostors);
  91922. };
  91923. /**
  91924. * Gets the current plugin used to run the simulation
  91925. * @returns current plugin
  91926. */
  91927. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  91928. return this._physicsPlugin;
  91929. };
  91930. /**
  91931. * Gets the list of physic impostors
  91932. * @returns an array of PhysicsImpostor
  91933. */
  91934. PhysicsEngine.prototype.getImpostors = function () {
  91935. return this._impostors;
  91936. };
  91937. /**
  91938. * Gets the impostor for a physics enabled object
  91939. * @param object defines the object impersonated by the impostor
  91940. * @returns the PhysicsImpostor or null if not found
  91941. */
  91942. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  91943. for (var i = 0; i < this._impostors.length; ++i) {
  91944. if (this._impostors[i].object === object) {
  91945. return this._impostors[i];
  91946. }
  91947. }
  91948. return null;
  91949. };
  91950. /**
  91951. * Gets the impostor for a physics body object
  91952. * @param body defines physics body used by the impostor
  91953. * @returns the PhysicsImpostor or null if not found
  91954. */
  91955. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  91956. for (var i = 0; i < this._impostors.length; ++i) {
  91957. if (this._impostors[i].physicsBody === body) {
  91958. return this._impostors[i];
  91959. }
  91960. }
  91961. return null;
  91962. };
  91963. /**
  91964. * Global value used to control the smallest number supported by the simulation
  91965. */
  91966. PhysicsEngine.Epsilon = 0.001;
  91967. return PhysicsEngine;
  91968. }());
  91969. BABYLON.PhysicsEngine = PhysicsEngine;
  91970. })(BABYLON || (BABYLON = {}));
  91971. //# sourceMappingURL=babylon.physicsEngine.js.map
  91972. var BABYLON;
  91973. (function (BABYLON) {
  91974. var PhysicsHelper = /** @class */ (function () {
  91975. function PhysicsHelper(scene) {
  91976. this._scene = scene;
  91977. this._physicsEngine = this._scene.getPhysicsEngine();
  91978. if (!this._physicsEngine) {
  91979. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  91980. }
  91981. }
  91982. /**
  91983. * @param {Vector3} origin the origin of the explosion
  91984. * @param {number} radius the explosion radius
  91985. * @param {number} strength the explosion strength
  91986. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  91987. */
  91988. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  91989. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91990. if (!this._physicsEngine) {
  91991. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  91992. return null;
  91993. }
  91994. var impostors = this._physicsEngine.getImpostors();
  91995. if (impostors.length === 0) {
  91996. return null;
  91997. }
  91998. var event = new PhysicsRadialExplosionEvent(this._scene);
  91999. impostors.forEach(function (impostor) {
  92000. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92001. if (!impostorForceAndContactPoint) {
  92002. return;
  92003. }
  92004. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92005. });
  92006. event.dispose(false);
  92007. return event;
  92008. };
  92009. /**
  92010. * @param {Vector3} origin the origin of the explosion
  92011. * @param {number} radius the explosion radius
  92012. * @param {number} strength the explosion strength
  92013. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92014. */
  92015. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  92016. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92017. if (!this._physicsEngine) {
  92018. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92019. return null;
  92020. }
  92021. var impostors = this._physicsEngine.getImpostors();
  92022. if (impostors.length === 0) {
  92023. return null;
  92024. }
  92025. var event = new PhysicsRadialExplosionEvent(this._scene);
  92026. impostors.forEach(function (impostor) {
  92027. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  92028. if (!impostorForceAndContactPoint) {
  92029. return;
  92030. }
  92031. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92032. });
  92033. event.dispose(false);
  92034. return event;
  92035. };
  92036. /**
  92037. * @param {Vector3} origin the origin of the explosion
  92038. * @param {number} radius the explosion radius
  92039. * @param {number} strength the explosion strength
  92040. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  92041. */
  92042. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  92043. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92044. if (!this._physicsEngine) {
  92045. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92046. return null;
  92047. }
  92048. var impostors = this._physicsEngine.getImpostors();
  92049. if (impostors.length === 0) {
  92050. return null;
  92051. }
  92052. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  92053. event.dispose(false);
  92054. return event;
  92055. };
  92056. /**
  92057. * @param {Vector3} origin the origin of the updraft
  92058. * @param {number} radius the radius of the updraft
  92059. * @param {number} strength the strength of the updraft
  92060. * @param {number} height the height of the updraft
  92061. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  92062. */
  92063. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  92064. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  92065. if (!this._physicsEngine) {
  92066. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92067. return null;
  92068. }
  92069. if (this._physicsEngine.getImpostors().length === 0) {
  92070. return null;
  92071. }
  92072. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  92073. event.dispose(false);
  92074. return event;
  92075. };
  92076. /**
  92077. * @param {Vector3} origin the of the vortex
  92078. * @param {number} radius the radius of the vortex
  92079. * @param {number} strength the strength of the vortex
  92080. * @param {number} height the height of the vortex
  92081. */
  92082. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  92083. if (!this._physicsEngine) {
  92084. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  92085. return null;
  92086. }
  92087. if (this._physicsEngine.getImpostors().length === 0) {
  92088. return null;
  92089. }
  92090. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  92091. event.dispose(false);
  92092. return event;
  92093. };
  92094. return PhysicsHelper;
  92095. }());
  92096. BABYLON.PhysicsHelper = PhysicsHelper;
  92097. /***** Radial explosion *****/
  92098. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  92099. function PhysicsRadialExplosionEvent(scene) {
  92100. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  92101. this._rays = [];
  92102. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  92103. this._scene = scene;
  92104. }
  92105. /**
  92106. * Returns the data related to the radial explosion event (sphere & rays).
  92107. * @returns {PhysicsRadialExplosionEventData}
  92108. */
  92109. PhysicsRadialExplosionEvent.prototype.getData = function () {
  92110. this._dataFetched = true;
  92111. return {
  92112. sphere: this._sphere,
  92113. rays: this._rays,
  92114. };
  92115. };
  92116. /**
  92117. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  92118. * @param impostor
  92119. * @param {Vector3} origin the origin of the explosion
  92120. * @param {number} radius the explosion radius
  92121. * @param {number} strength the explosion strength
  92122. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  92123. * @returns {Nullable<PhysicsForceAndContactPoint>}
  92124. */
  92125. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  92126. if (impostor.mass === 0) {
  92127. return null;
  92128. }
  92129. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  92130. return null;
  92131. }
  92132. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92133. return null;
  92134. }
  92135. var impostorObjectCenter = impostor.getObjectCenter();
  92136. var direction = impostorObjectCenter.subtract(origin);
  92137. var ray = new BABYLON.Ray(origin, direction, radius);
  92138. this._rays.push(ray);
  92139. var hit = ray.intersectsMesh(impostor.object);
  92140. var contactPoint = hit.pickedPoint;
  92141. if (!contactPoint) {
  92142. return null;
  92143. }
  92144. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  92145. if (distanceFromOrigin > radius) {
  92146. return null;
  92147. }
  92148. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  92149. ? strength
  92150. : strength * (1 - (distanceFromOrigin / radius));
  92151. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92152. return { force: force, contactPoint: contactPoint };
  92153. };
  92154. /**
  92155. * Disposes the sphere.
  92156. * @param {bolean} force
  92157. */
  92158. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  92159. var _this = this;
  92160. if (force === void 0) { force = true; }
  92161. if (force) {
  92162. this._sphere.dispose();
  92163. }
  92164. else {
  92165. setTimeout(function () {
  92166. if (!_this._dataFetched) {
  92167. _this._sphere.dispose();
  92168. }
  92169. }, 0);
  92170. }
  92171. };
  92172. /*** Helpers ***/
  92173. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  92174. if (!this._sphere) {
  92175. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  92176. this._sphere.isVisible = false;
  92177. }
  92178. };
  92179. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  92180. var impostorObject = impostor.object;
  92181. this._prepareSphere();
  92182. this._sphere.position = origin;
  92183. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  92184. this._sphere._updateBoundingInfo();
  92185. this._sphere.computeWorldMatrix(true);
  92186. return this._sphere.intersectsMesh(impostorObject, true);
  92187. };
  92188. return PhysicsRadialExplosionEvent;
  92189. }());
  92190. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  92191. /***** Gravitational Field *****/
  92192. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  92193. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  92194. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  92195. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92196. this._physicsHelper = physicsHelper;
  92197. this._scene = scene;
  92198. this._origin = origin;
  92199. this._radius = radius;
  92200. this._strength = strength;
  92201. this._falloff = falloff;
  92202. this._tickCallback = this._tick.bind(this);
  92203. }
  92204. /**
  92205. * Returns the data related to the gravitational field event (sphere).
  92206. * @returns {PhysicsGravitationalFieldEventData}
  92207. */
  92208. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  92209. this._dataFetched = true;
  92210. return {
  92211. sphere: this._sphere,
  92212. };
  92213. };
  92214. /**
  92215. * Enables the gravitational field.
  92216. */
  92217. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  92218. this._tickCallback.call(this);
  92219. this._scene.registerBeforeRender(this._tickCallback);
  92220. };
  92221. /**
  92222. * Disables the gravitational field.
  92223. */
  92224. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  92225. this._scene.unregisterBeforeRender(this._tickCallback);
  92226. };
  92227. /**
  92228. * Disposes the sphere.
  92229. * @param {bolean} force
  92230. */
  92231. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  92232. var _this = this;
  92233. if (force === void 0) { force = true; }
  92234. if (force) {
  92235. this._sphere.dispose();
  92236. }
  92237. else {
  92238. setTimeout(function () {
  92239. if (!_this._dataFetched) {
  92240. _this._sphere.dispose();
  92241. }
  92242. }, 0);
  92243. }
  92244. };
  92245. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  92246. // Since the params won't change, we fetch the event only once
  92247. if (this._sphere) {
  92248. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92249. }
  92250. else {
  92251. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  92252. if (radialExplosionEvent) {
  92253. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  92254. }
  92255. }
  92256. };
  92257. return PhysicsGravitationalFieldEvent;
  92258. }());
  92259. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  92260. /***** Updraft *****/
  92261. var PhysicsUpdraftEvent = /** @class */ (function () {
  92262. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  92263. this._scene = _scene;
  92264. this._origin = _origin;
  92265. this._radius = _radius;
  92266. this._strength = _strength;
  92267. this._height = _height;
  92268. this._updraftMode = _updraftMode;
  92269. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92270. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  92271. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92272. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92273. this._physicsEngine = this._scene.getPhysicsEngine();
  92274. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92275. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92276. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92277. this._originDirection = this._origin.subtract(this._originTop).normalize();
  92278. }
  92279. this._tickCallback = this._tick.bind(this);
  92280. }
  92281. /**
  92282. * Returns the data related to the updraft event (cylinder).
  92283. * @returns {PhysicsUpdraftEventData}
  92284. */
  92285. PhysicsUpdraftEvent.prototype.getData = function () {
  92286. this._dataFetched = true;
  92287. return {
  92288. cylinder: this._cylinder,
  92289. };
  92290. };
  92291. /**
  92292. * Enables the updraft.
  92293. */
  92294. PhysicsUpdraftEvent.prototype.enable = function () {
  92295. this._tickCallback.call(this);
  92296. this._scene.registerBeforeRender(this._tickCallback);
  92297. };
  92298. /**
  92299. * Disables the cortex.
  92300. */
  92301. PhysicsUpdraftEvent.prototype.disable = function () {
  92302. this._scene.unregisterBeforeRender(this._tickCallback);
  92303. };
  92304. /**
  92305. * Disposes the sphere.
  92306. * @param {bolean} force
  92307. */
  92308. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  92309. var _this = this;
  92310. if (force === void 0) { force = true; }
  92311. if (force) {
  92312. this._cylinder.dispose();
  92313. }
  92314. else {
  92315. setTimeout(function () {
  92316. if (!_this._dataFetched) {
  92317. _this._cylinder.dispose();
  92318. }
  92319. }, 0);
  92320. }
  92321. };
  92322. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92323. if (impostor.mass === 0) {
  92324. return null;
  92325. }
  92326. if (!this._intersectsWithCylinder(impostor)) {
  92327. return null;
  92328. }
  92329. var impostorObjectCenter = impostor.getObjectCenter();
  92330. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  92331. var direction = this._originDirection;
  92332. }
  92333. else {
  92334. var direction = impostorObjectCenter.subtract(this._originTop);
  92335. }
  92336. var multiplier = this._strength * -1;
  92337. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  92338. return { force: force, contactPoint: impostorObjectCenter };
  92339. };
  92340. PhysicsUpdraftEvent.prototype._tick = function () {
  92341. var _this = this;
  92342. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92343. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92344. if (!impostorForceAndContactPoint) {
  92345. return;
  92346. }
  92347. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92348. });
  92349. };
  92350. /*** Helpers ***/
  92351. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  92352. if (!this._cylinder) {
  92353. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  92354. height: this._height,
  92355. diameter: this._radius * 2,
  92356. }, this._scene);
  92357. this._cylinder.isVisible = false;
  92358. }
  92359. };
  92360. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  92361. var impostorObject = impostor.object;
  92362. this._prepareCylinder();
  92363. this._cylinder.position = this._cylinderPosition;
  92364. return this._cylinder.intersectsMesh(impostorObject, true);
  92365. };
  92366. return PhysicsUpdraftEvent;
  92367. }());
  92368. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  92369. /***** Vortex *****/
  92370. var PhysicsVortexEvent = /** @class */ (function () {
  92371. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  92372. this._scene = _scene;
  92373. this._origin = _origin;
  92374. this._radius = _radius;
  92375. this._strength = _strength;
  92376. this._height = _height;
  92377. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  92378. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  92379. this._updraftMultiplier = 0.02;
  92380. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  92381. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  92382. this._physicsEngine = this._scene.getPhysicsEngine();
  92383. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  92384. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  92385. this._tickCallback = this._tick.bind(this);
  92386. }
  92387. /**
  92388. * Returns the data related to the vortex event (cylinder).
  92389. * @returns {PhysicsVortexEventData}
  92390. */
  92391. PhysicsVortexEvent.prototype.getData = function () {
  92392. this._dataFetched = true;
  92393. return {
  92394. cylinder: this._cylinder,
  92395. };
  92396. };
  92397. /**
  92398. * Enables the vortex.
  92399. */
  92400. PhysicsVortexEvent.prototype.enable = function () {
  92401. this._tickCallback.call(this);
  92402. this._scene.registerBeforeRender(this._tickCallback);
  92403. };
  92404. /**
  92405. * Disables the cortex.
  92406. */
  92407. PhysicsVortexEvent.prototype.disable = function () {
  92408. this._scene.unregisterBeforeRender(this._tickCallback);
  92409. };
  92410. /**
  92411. * Disposes the sphere.
  92412. * @param {bolean} force
  92413. */
  92414. PhysicsVortexEvent.prototype.dispose = function (force) {
  92415. var _this = this;
  92416. if (force === void 0) { force = true; }
  92417. if (force) {
  92418. this._cylinder.dispose();
  92419. }
  92420. else {
  92421. setTimeout(function () {
  92422. if (!_this._dataFetched) {
  92423. _this._cylinder.dispose();
  92424. }
  92425. }, 0);
  92426. }
  92427. };
  92428. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  92429. if (impostor.mass === 0) {
  92430. return null;
  92431. }
  92432. if (!this._intersectsWithCylinder(impostor)) {
  92433. return null;
  92434. }
  92435. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  92436. return null;
  92437. }
  92438. var impostorObjectCenter = impostor.getObjectCenter();
  92439. 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)
  92440. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  92441. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  92442. var hit = ray.intersectsMesh(impostor.object);
  92443. var contactPoint = hit.pickedPoint;
  92444. if (!contactPoint) {
  92445. return null;
  92446. }
  92447. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  92448. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  92449. var directionToOrigin = contactPoint.normalize();
  92450. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92451. directionToOrigin = directionToOrigin.negate();
  92452. }
  92453. // TODO: find a more physically based solution
  92454. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  92455. var forceX = directionToOrigin.x * this._strength / 8;
  92456. var forceY = directionToOrigin.y * this._updraftMultiplier;
  92457. var forceZ = directionToOrigin.z * this._strength / 8;
  92458. }
  92459. else {
  92460. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  92461. var forceY = this._originTop.y * this._updraftMultiplier;
  92462. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  92463. }
  92464. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  92465. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  92466. return { force: force, contactPoint: impostorObjectCenter };
  92467. };
  92468. PhysicsVortexEvent.prototype._tick = function () {
  92469. var _this = this;
  92470. this._physicsEngine.getImpostors().forEach(function (impostor) {
  92471. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  92472. if (!impostorForceAndContactPoint) {
  92473. return;
  92474. }
  92475. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  92476. });
  92477. };
  92478. /*** Helpers ***/
  92479. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  92480. if (!this._cylinder) {
  92481. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  92482. height: this._height,
  92483. diameter: this._radius * 2,
  92484. }, this._scene);
  92485. this._cylinder.isVisible = false;
  92486. }
  92487. };
  92488. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  92489. var impostorObject = impostor.object;
  92490. this._prepareCylinder();
  92491. this._cylinder.position = this._cylinderPosition;
  92492. return this._cylinder.intersectsMesh(impostorObject, true);
  92493. };
  92494. return PhysicsVortexEvent;
  92495. }());
  92496. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  92497. /***** Enums *****/
  92498. /**
  92499. * The strenght of the force in correspondence to the distance of the affected object
  92500. */
  92501. var PhysicsRadialImpulseFalloff;
  92502. (function (PhysicsRadialImpulseFalloff) {
  92503. /** Defines that impulse is constant in strength across it's whole radius */
  92504. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  92505. /** DEfines that impulse gets weaker if it's further from the origin */
  92506. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  92507. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  92508. /**
  92509. * The strenght of the force in correspondence to the distance of the affected object
  92510. */
  92511. var PhysicsUpdraftMode;
  92512. (function (PhysicsUpdraftMode) {
  92513. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  92514. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  92515. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  92516. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  92517. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  92518. })(BABYLON || (BABYLON = {}));
  92519. //# sourceMappingURL=babylon.physicsHelper.js.map
  92520. var BABYLON;
  92521. (function (BABYLON) {
  92522. /** @hidden */
  92523. var CannonJSPlugin = /** @class */ (function () {
  92524. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  92525. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  92526. if (iterations === void 0) { iterations = 10; }
  92527. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  92528. this.name = "CannonJSPlugin";
  92529. this._physicsMaterials = new Array();
  92530. this._fixedTimeStep = 1 / 60;
  92531. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  92532. this.BJSCANNON = CANNON;
  92533. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  92534. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  92535. this._tmpPosition = BABYLON.Vector3.Zero();
  92536. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  92537. this._tmpUnityRotation = new BABYLON.Quaternion();
  92538. if (!this.isSupported()) {
  92539. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  92540. return;
  92541. }
  92542. this._extendNamespace();
  92543. this.world = new this.BJSCANNON.World();
  92544. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  92545. this.world.solver.iterations = iterations;
  92546. }
  92547. CannonJSPlugin.prototype.setGravity = function (gravity) {
  92548. this.world.gravity.copy(gravity);
  92549. };
  92550. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  92551. this._fixedTimeStep = timeStep;
  92552. };
  92553. CannonJSPlugin.prototype.getTimeStep = function () {
  92554. return this._fixedTimeStep;
  92555. };
  92556. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  92557. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  92558. };
  92559. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92560. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92561. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92562. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  92563. };
  92564. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92565. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  92566. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  92567. impostor.physicsBody.applyForce(impulse, worldPoint);
  92568. };
  92569. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92570. //parent-child relationship. Does this impostor has a parent impostor?
  92571. if (impostor.parent) {
  92572. if (impostor.physicsBody) {
  92573. this.removePhysicsBody(impostor);
  92574. //TODO is that needed?
  92575. impostor.forceUpdate();
  92576. }
  92577. return;
  92578. }
  92579. //should a new body be created for this impostor?
  92580. if (impostor.isBodyInitRequired()) {
  92581. var shape = this._createShape(impostor);
  92582. //unregister events, if body is being changed
  92583. var oldBody = impostor.physicsBody;
  92584. if (oldBody) {
  92585. this.removePhysicsBody(impostor);
  92586. }
  92587. //create the body and material
  92588. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  92589. var bodyCreationObject = {
  92590. mass: impostor.getParam("mass"),
  92591. material: material
  92592. };
  92593. // A simple extend, in case native options were used.
  92594. var nativeOptions = impostor.getParam("nativeOptions");
  92595. for (var key in nativeOptions) {
  92596. if (nativeOptions.hasOwnProperty(key)) {
  92597. bodyCreationObject[key] = nativeOptions[key];
  92598. }
  92599. }
  92600. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  92601. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  92602. this.world.addEventListener("preStep", impostor.beforeStep);
  92603. this.world.addEventListener("postStep", impostor.afterStep);
  92604. impostor.physicsBody.addShape(shape);
  92605. this.world.add(impostor.physicsBody);
  92606. //try to keep the body moving in the right direction by taking old properties.
  92607. //Should be tested!
  92608. if (oldBody) {
  92609. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  92610. impostor.physicsBody[param].copy(oldBody[param]);
  92611. });
  92612. }
  92613. this._processChildMeshes(impostor);
  92614. }
  92615. //now update the body's transformation
  92616. this._updatePhysicsBodyTransformation(impostor);
  92617. };
  92618. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  92619. var _this = this;
  92620. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  92621. var currentRotation = mainImpostor.object.rotationQuaternion;
  92622. if (meshChildren.length) {
  92623. var processMesh = function (localPosition, mesh) {
  92624. if (!currentRotation || !mesh.rotationQuaternion) {
  92625. return;
  92626. }
  92627. var childImpostor = mesh.getPhysicsImpostor();
  92628. if (childImpostor) {
  92629. var parent = childImpostor.parent;
  92630. if (parent !== mainImpostor) {
  92631. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  92632. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  92633. if (childImpostor.physicsBody) {
  92634. _this.removePhysicsBody(childImpostor);
  92635. childImpostor.physicsBody = null;
  92636. }
  92637. childImpostor.parent = mainImpostor;
  92638. childImpostor.resetUpdateFlags();
  92639. 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));
  92640. //Add the mass of the children.
  92641. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  92642. }
  92643. }
  92644. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  92645. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  92646. };
  92647. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  92648. }
  92649. };
  92650. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92651. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  92652. this.world.removeEventListener("preStep", impostor.beforeStep);
  92653. this.world.removeEventListener("postStep", impostor.afterStep);
  92654. this.world.remove(impostor.physicsBody);
  92655. };
  92656. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92657. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92658. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92659. if (!mainBody || !connectedBody) {
  92660. return;
  92661. }
  92662. var constraint;
  92663. var jointData = impostorJoint.joint.jointData;
  92664. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  92665. var constraintData = {
  92666. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  92667. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  92668. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  92669. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  92670. maxForce: jointData.nativeParams.maxForce,
  92671. collideConnected: !!jointData.collision
  92672. };
  92673. switch (impostorJoint.joint.type) {
  92674. case BABYLON.PhysicsJoint.HingeJoint:
  92675. case BABYLON.PhysicsJoint.Hinge2Joint:
  92676. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  92677. break;
  92678. case BABYLON.PhysicsJoint.DistanceJoint:
  92679. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  92680. break;
  92681. case BABYLON.PhysicsJoint.SpringJoint:
  92682. var springData = jointData;
  92683. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  92684. restLength: springData.length,
  92685. stiffness: springData.stiffness,
  92686. damping: springData.damping,
  92687. localAnchorA: constraintData.pivotA,
  92688. localAnchorB: constraintData.pivotB
  92689. });
  92690. break;
  92691. case BABYLON.PhysicsJoint.LockJoint:
  92692. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  92693. break;
  92694. case BABYLON.PhysicsJoint.PointToPointJoint:
  92695. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92696. default:
  92697. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  92698. break;
  92699. }
  92700. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  92701. constraint.collideConnected = !!jointData.collision;
  92702. impostorJoint.joint.physicsJoint = constraint;
  92703. //don't add spring as constraint, as it is not one.
  92704. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92705. this.world.addConstraint(constraint);
  92706. }
  92707. else {
  92708. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  92709. constraint.applyForce();
  92710. };
  92711. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92712. }
  92713. };
  92714. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92715. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  92716. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  92717. }
  92718. else {
  92719. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  92720. }
  92721. };
  92722. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  92723. var index;
  92724. var mat;
  92725. for (index = 0; index < this._physicsMaterials.length; index++) {
  92726. mat = this._physicsMaterials[index];
  92727. if (mat.friction === friction && mat.restitution === restitution) {
  92728. return mat;
  92729. }
  92730. }
  92731. var currentMat = new this.BJSCANNON.Material(name);
  92732. currentMat.friction = friction;
  92733. currentMat.restitution = restitution;
  92734. this._physicsMaterials.push(currentMat);
  92735. return currentMat;
  92736. };
  92737. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  92738. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  92739. };
  92740. CannonJSPlugin.prototype._createShape = function (impostor) {
  92741. var object = impostor.object;
  92742. var returnValue;
  92743. var extendSize = impostor.getObjectExtendSize();
  92744. switch (impostor.type) {
  92745. case BABYLON.PhysicsImpostor.SphereImpostor:
  92746. var radiusX = extendSize.x;
  92747. var radiusY = extendSize.y;
  92748. var radiusZ = extendSize.z;
  92749. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  92750. break;
  92751. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  92752. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92753. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  92754. break;
  92755. case BABYLON.PhysicsImpostor.BoxImpostor:
  92756. var box = extendSize.scale(0.5);
  92757. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  92758. break;
  92759. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92760. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  92761. returnValue = new this.BJSCANNON.Plane();
  92762. break;
  92763. case BABYLON.PhysicsImpostor.MeshImpostor:
  92764. // should transform the vertex data to world coordinates!!
  92765. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  92766. var rawFaces = object.getIndices ? object.getIndices() : [];
  92767. if (!rawVerts)
  92768. return;
  92769. // get only scale! so the object could transform correctly.
  92770. var oldPosition = object.position.clone();
  92771. var oldRotation = object.rotation && object.rotation.clone();
  92772. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  92773. object.position.copyFromFloats(0, 0, 0);
  92774. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92775. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92776. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92777. var transform = object.computeWorldMatrix(true);
  92778. // convert rawVerts to object space
  92779. var temp = new Array();
  92780. var index;
  92781. for (index = 0; index < rawVerts.length; index += 3) {
  92782. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  92783. }
  92784. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  92785. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  92786. //now set back the transformation!
  92787. object.position.copyFrom(oldPosition);
  92788. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  92789. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  92790. break;
  92791. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  92792. var oldPosition2 = object.position.clone();
  92793. var oldRotation2 = object.rotation && object.rotation.clone();
  92794. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  92795. object.position.copyFromFloats(0, 0, 0);
  92796. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  92797. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  92798. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  92799. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  92800. returnValue = this._createHeightmap(object);
  92801. object.position.copyFrom(oldPosition2);
  92802. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  92803. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  92804. object.computeWorldMatrix(true);
  92805. break;
  92806. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92807. returnValue = new this.BJSCANNON.Particle();
  92808. break;
  92809. }
  92810. return returnValue;
  92811. };
  92812. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  92813. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  92814. var transform = object.computeWorldMatrix(true);
  92815. // convert rawVerts to object space
  92816. var temp = new Array();
  92817. var index;
  92818. for (index = 0; index < pos.length; index += 3) {
  92819. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  92820. }
  92821. pos = temp;
  92822. var matrix = new Array();
  92823. //For now pointDepth will not be used and will be automatically calculated.
  92824. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  92825. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  92826. var boundingInfo = object.getBoundingInfo();
  92827. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  92828. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  92829. var elementSize = dim * 2 / arraySize;
  92830. for (var i = 0; i < pos.length; i = i + 3) {
  92831. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  92832. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  92833. var y = -pos[i + 2] + minY;
  92834. if (!matrix[x]) {
  92835. matrix[x] = [];
  92836. }
  92837. if (!matrix[x][z]) {
  92838. matrix[x][z] = y;
  92839. }
  92840. matrix[x][z] = Math.max(y, matrix[x][z]);
  92841. }
  92842. for (var x = 0; x <= arraySize; ++x) {
  92843. if (!matrix[x]) {
  92844. var loc = 1;
  92845. while (!matrix[(x + loc) % arraySize]) {
  92846. loc++;
  92847. }
  92848. matrix[x] = matrix[(x + loc) % arraySize].slice();
  92849. //console.log("missing x", x);
  92850. }
  92851. for (var z = 0; z <= arraySize; ++z) {
  92852. if (!matrix[x][z]) {
  92853. var loc = 1;
  92854. var newValue;
  92855. while (newValue === undefined) {
  92856. newValue = matrix[x][(z + loc++) % arraySize];
  92857. }
  92858. matrix[x][z] = newValue;
  92859. }
  92860. }
  92861. }
  92862. var shape = new this.BJSCANNON.Heightfield(matrix, {
  92863. elementSize: elementSize
  92864. });
  92865. //For future reference, needed for body transformation
  92866. shape.minY = minY;
  92867. return shape;
  92868. };
  92869. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  92870. var object = impostor.object;
  92871. //make sure it is updated...
  92872. object.computeWorldMatrix && object.computeWorldMatrix(true);
  92873. // The delta between the mesh position and the mesh bounding box center
  92874. var bInfo = object.getBoundingInfo();
  92875. if (!bInfo)
  92876. return;
  92877. var center = impostor.getObjectCenter();
  92878. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  92879. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  92880. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  92881. this._tmpPosition.copyFrom(center);
  92882. var quaternion = object.rotationQuaternion;
  92883. if (!quaternion) {
  92884. return;
  92885. }
  92886. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  92887. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  92888. //-90 DEG in X, precalculated
  92889. quaternion = quaternion.multiply(this._minus90X);
  92890. //Invert! (Precalculated, 90 deg in X)
  92891. //No need to clone. this will never change.
  92892. impostor.setDeltaRotation(this._plus90X);
  92893. }
  92894. //If it is a heightfield, if should be centered.
  92895. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  92896. var mesh = object;
  92897. var boundingInfo = mesh.getBoundingInfo();
  92898. //calculate the correct body position:
  92899. var rotationQuaternion = mesh.rotationQuaternion;
  92900. mesh.rotationQuaternion = this._tmpUnityRotation;
  92901. mesh.computeWorldMatrix(true);
  92902. //get original center with no rotation
  92903. var c = center.clone();
  92904. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  92905. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  92906. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  92907. mesh.setPreTransformMatrix(p);
  92908. mesh.computeWorldMatrix(true);
  92909. //calculate the translation
  92910. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  92911. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  92912. //add it inverted to the delta
  92913. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  92914. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  92915. //rotation is back
  92916. mesh.rotationQuaternion = rotationQuaternion;
  92917. mesh.setPreTransformMatrix(oldPivot);
  92918. mesh.computeWorldMatrix(true);
  92919. }
  92920. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  92921. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  92922. //this._tmpPosition.copyFrom(object.position);
  92923. }
  92924. impostor.setDeltaPosition(this._tmpDeltaPosition);
  92925. //Now update the impostor object
  92926. impostor.physicsBody.position.copy(this._tmpPosition);
  92927. impostor.physicsBody.quaternion.copy(quaternion);
  92928. };
  92929. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92930. impostor.object.position.copyFrom(impostor.physicsBody.position);
  92931. if (impostor.object.rotationQuaternion) {
  92932. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  92933. }
  92934. };
  92935. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92936. impostor.physicsBody.position.copy(newPosition);
  92937. impostor.physicsBody.quaternion.copy(newRotation);
  92938. };
  92939. CannonJSPlugin.prototype.isSupported = function () {
  92940. return this.BJSCANNON !== undefined;
  92941. };
  92942. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92943. impostor.physicsBody.velocity.copy(velocity);
  92944. };
  92945. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92946. impostor.physicsBody.angularVelocity.copy(velocity);
  92947. };
  92948. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92949. var v = impostor.physicsBody.velocity;
  92950. if (!v) {
  92951. return null;
  92952. }
  92953. return new BABYLON.Vector3(v.x, v.y, v.z);
  92954. };
  92955. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92956. var v = impostor.physicsBody.angularVelocity;
  92957. if (!v) {
  92958. return null;
  92959. }
  92960. return new BABYLON.Vector3(v.x, v.y, v.z);
  92961. };
  92962. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92963. impostor.physicsBody.mass = mass;
  92964. impostor.physicsBody.updateMassProperties();
  92965. };
  92966. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  92967. return impostor.physicsBody.mass;
  92968. };
  92969. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  92970. return impostor.physicsBody.material.friction;
  92971. };
  92972. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92973. impostor.physicsBody.material.friction = friction;
  92974. };
  92975. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92976. return impostor.physicsBody.material.restitution;
  92977. };
  92978. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92979. impostor.physicsBody.material.restitution = restitution;
  92980. };
  92981. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  92982. impostor.physicsBody.sleep();
  92983. };
  92984. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  92985. impostor.physicsBody.wakeUp();
  92986. };
  92987. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92988. joint.physicsJoint.distance = maxDistance;
  92989. };
  92990. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92991. // if (!motorIndex) {
  92992. // joint.physicsJoint.enableMotor();
  92993. // }
  92994. // }
  92995. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  92996. // if (!motorIndex) {
  92997. // joint.physicsJoint.disableMotor();
  92998. // }
  92999. // }
  93000. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93001. if (!motorIndex) {
  93002. joint.physicsJoint.enableMotor();
  93003. joint.physicsJoint.setMotorSpeed(speed);
  93004. if (maxForce) {
  93005. this.setLimit(joint, maxForce);
  93006. }
  93007. }
  93008. };
  93009. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  93010. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  93011. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  93012. };
  93013. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93014. var body = impostor.physicsBody;
  93015. mesh.position.x = body.position.x;
  93016. mesh.position.y = body.position.y;
  93017. mesh.position.z = body.position.z;
  93018. if (mesh.rotationQuaternion) {
  93019. mesh.rotationQuaternion.x = body.quaternion.x;
  93020. mesh.rotationQuaternion.y = body.quaternion.y;
  93021. mesh.rotationQuaternion.z = body.quaternion.z;
  93022. mesh.rotationQuaternion.w = body.quaternion.w;
  93023. }
  93024. };
  93025. CannonJSPlugin.prototype.getRadius = function (impostor) {
  93026. var shape = impostor.physicsBody.shapes[0];
  93027. return shape.boundingSphereRadius;
  93028. };
  93029. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93030. var shape = impostor.physicsBody.shapes[0];
  93031. result.x = shape.halfExtents.x * 2;
  93032. result.y = shape.halfExtents.y * 2;
  93033. result.z = shape.halfExtents.z * 2;
  93034. };
  93035. CannonJSPlugin.prototype.dispose = function () {
  93036. };
  93037. CannonJSPlugin.prototype._extendNamespace = function () {
  93038. //this will force cannon to execute at least one step when using interpolation
  93039. var step_tmp1 = new this.BJSCANNON.Vec3();
  93040. var Engine = this.BJSCANNON;
  93041. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  93042. maxSubSteps = maxSubSteps || 10;
  93043. timeSinceLastCalled = timeSinceLastCalled || 0;
  93044. if (timeSinceLastCalled === 0) {
  93045. this.internalStep(dt);
  93046. this.time += dt;
  93047. }
  93048. else {
  93049. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  93050. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  93051. var t0 = performance.now();
  93052. for (var i = 0; i !== internalSteps; i++) {
  93053. this.internalStep(dt);
  93054. if (performance.now() - t0 > dt * 1000) {
  93055. break;
  93056. }
  93057. }
  93058. this.time += timeSinceLastCalled;
  93059. var h = this.time % dt;
  93060. var h_div_dt = h / dt;
  93061. var interpvelo = step_tmp1;
  93062. var bodies = this.bodies;
  93063. for (var j = 0; j !== bodies.length; j++) {
  93064. var b = bodies[j];
  93065. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  93066. b.position.vsub(b.previousPosition, interpvelo);
  93067. interpvelo.scale(h_div_dt, interpvelo);
  93068. b.position.vadd(interpvelo, b.interpolatedPosition);
  93069. }
  93070. else {
  93071. b.interpolatedPosition.copy(b.position);
  93072. b.interpolatedQuaternion.copy(b.quaternion);
  93073. }
  93074. }
  93075. }
  93076. };
  93077. };
  93078. return CannonJSPlugin;
  93079. }());
  93080. BABYLON.CannonJSPlugin = CannonJSPlugin;
  93081. })(BABYLON || (BABYLON = {}));
  93082. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  93083. var BABYLON;
  93084. (function (BABYLON) {
  93085. /** @hidden */
  93086. var OimoJSPlugin = /** @class */ (function () {
  93087. function OimoJSPlugin(iterations) {
  93088. this.name = "OimoJSPlugin";
  93089. this._tmpImpostorsArray = [];
  93090. this._tmpPositionVector = BABYLON.Vector3.Zero();
  93091. this.BJSOIMO = OIMO;
  93092. this.world = new this.BJSOIMO.World({
  93093. iterations: iterations
  93094. });
  93095. this.world.clear();
  93096. }
  93097. OimoJSPlugin.prototype.setGravity = function (gravity) {
  93098. this.world.gravity.copy(gravity);
  93099. };
  93100. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  93101. this.world.timeStep = timeStep;
  93102. };
  93103. OimoJSPlugin.prototype.getTimeStep = function () {
  93104. return this.world.timeStep;
  93105. };
  93106. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  93107. var _this = this;
  93108. impostors.forEach(function (impostor) {
  93109. impostor.beforeStep();
  93110. });
  93111. this.world.step();
  93112. impostors.forEach(function (impostor) {
  93113. impostor.afterStep();
  93114. //update the ordered impostors array
  93115. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  93116. });
  93117. //check for collisions
  93118. var contact = this.world.contacts;
  93119. while (contact !== null) {
  93120. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  93121. contact = contact.next;
  93122. continue;
  93123. }
  93124. //is this body colliding with any other? get the impostor
  93125. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  93126. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  93127. if (!mainImpostor || !collidingImpostor) {
  93128. contact = contact.next;
  93129. continue;
  93130. }
  93131. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  93132. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  93133. contact = contact.next;
  93134. }
  93135. };
  93136. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  93137. var mass = impostor.physicsBody.mass;
  93138. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  93139. };
  93140. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  93141. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  93142. this.applyImpulse(impostor, force, contactPoint);
  93143. };
  93144. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  93145. var _this = this;
  93146. //parent-child relationship. Does this impostor has a parent impostor?
  93147. if (impostor.parent) {
  93148. if (impostor.physicsBody) {
  93149. this.removePhysicsBody(impostor);
  93150. //TODO is that needed?
  93151. impostor.forceUpdate();
  93152. }
  93153. return;
  93154. }
  93155. if (impostor.isBodyInitRequired()) {
  93156. var bodyConfig = {
  93157. name: impostor.uniqueId,
  93158. //Oimo must have mass, also for static objects.
  93159. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  93160. size: [],
  93161. type: [],
  93162. pos: [],
  93163. posShape: [],
  93164. rot: [],
  93165. rotShape: [],
  93166. move: impostor.getParam("mass") !== 0,
  93167. density: impostor.getParam("mass"),
  93168. friction: impostor.getParam("friction"),
  93169. restitution: impostor.getParam("restitution"),
  93170. //Supporting older versions of Oimo
  93171. world: this.world
  93172. };
  93173. var impostors = [impostor];
  93174. var addToArray = function (parent) {
  93175. if (!parent.getChildMeshes)
  93176. return;
  93177. parent.getChildMeshes().forEach(function (m) {
  93178. if (m.physicsImpostor) {
  93179. impostors.push(m.physicsImpostor);
  93180. //m.physicsImpostor._init();
  93181. }
  93182. });
  93183. };
  93184. addToArray(impostor.object);
  93185. var checkWithEpsilon_1 = function (value) {
  93186. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  93187. };
  93188. var globalQuaternion_1 = new BABYLON.Quaternion();
  93189. impostors.forEach(function (i) {
  93190. if (!i.object.rotationQuaternion) {
  93191. return;
  93192. }
  93193. //get the correct bounding box
  93194. var oldQuaternion = i.object.rotationQuaternion;
  93195. globalQuaternion_1 = oldQuaternion.clone();
  93196. var rot = oldQuaternion.toEulerAngles();
  93197. var extendSize = i.getObjectExtendSize();
  93198. var radToDeg = 57.295779513082320876;
  93199. if (i === impostor) {
  93200. var center = impostor.getObjectCenter();
  93201. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  93202. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  93203. //Can also use Array.prototype.push.apply
  93204. bodyConfig.pos.push(center.x);
  93205. bodyConfig.pos.push(center.y);
  93206. bodyConfig.pos.push(center.z);
  93207. bodyConfig.posShape.push(0, 0, 0);
  93208. //tmp solution
  93209. bodyConfig.rot.push(0);
  93210. bodyConfig.rot.push(0);
  93211. bodyConfig.rot.push(0);
  93212. bodyConfig.rotShape.push(0, 0, 0);
  93213. }
  93214. else {
  93215. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  93216. bodyConfig.posShape.push(localPosition.x);
  93217. bodyConfig.posShape.push(localPosition.y);
  93218. bodyConfig.posShape.push(localPosition.z);
  93219. bodyConfig.pos.push(0, 0, 0);
  93220. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  93221. bodyConfig.rot.push(0);
  93222. bodyConfig.rot.push(0);
  93223. bodyConfig.rot.push(0);
  93224. bodyConfig.rotShape.push(rot.x * radToDeg);
  93225. bodyConfig.rotShape.push(rot.y * radToDeg);
  93226. bodyConfig.rotShape.push(rot.z * radToDeg);
  93227. }
  93228. // register mesh
  93229. switch (i.type) {
  93230. case BABYLON.PhysicsImpostor.ParticleImpostor:
  93231. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  93232. case BABYLON.PhysicsImpostor.SphereImpostor:
  93233. var radiusX = extendSize.x;
  93234. var radiusY = extendSize.y;
  93235. var radiusZ = extendSize.z;
  93236. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  93237. bodyConfig.type.push('sphere');
  93238. //due to the way oimo works with compounds, add 3 times
  93239. bodyConfig.size.push(size);
  93240. bodyConfig.size.push(size);
  93241. bodyConfig.size.push(size);
  93242. break;
  93243. case BABYLON.PhysicsImpostor.CylinderImpostor:
  93244. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  93245. var sizeY = checkWithEpsilon_1(extendSize.y);
  93246. bodyConfig.type.push('cylinder');
  93247. bodyConfig.size.push(sizeX);
  93248. bodyConfig.size.push(sizeY);
  93249. //due to the way oimo works with compounds, add one more value.
  93250. bodyConfig.size.push(sizeY);
  93251. break;
  93252. case BABYLON.PhysicsImpostor.PlaneImpostor:
  93253. case BABYLON.PhysicsImpostor.BoxImpostor:
  93254. default:
  93255. var sizeX = checkWithEpsilon_1(extendSize.x);
  93256. var sizeY = checkWithEpsilon_1(extendSize.y);
  93257. var sizeZ = checkWithEpsilon_1(extendSize.z);
  93258. bodyConfig.type.push('box');
  93259. //if (i === impostor) {
  93260. bodyConfig.size.push(sizeX);
  93261. bodyConfig.size.push(sizeY);
  93262. bodyConfig.size.push(sizeZ);
  93263. //} else {
  93264. // bodyConfig.size.push(0,0,0);
  93265. //}
  93266. break;
  93267. }
  93268. //actually not needed, but hey...
  93269. i.object.rotationQuaternion = oldQuaternion;
  93270. });
  93271. impostor.physicsBody = this.world.add(bodyConfig);
  93272. // set the quaternion, ignoring the previously defined (euler) rotation
  93273. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  93274. // update with delta 0, so the body will reveive the new rotation.
  93275. impostor.physicsBody.updatePosition(0);
  93276. }
  93277. else {
  93278. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  93279. }
  93280. impostor.setDeltaPosition(this._tmpPositionVector);
  93281. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  93282. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  93283. };
  93284. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  93285. //impostor.physicsBody.dispose();
  93286. //Same as : (older oimo versions)
  93287. this.world.removeRigidBody(impostor.physicsBody);
  93288. };
  93289. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  93290. var mainBody = impostorJoint.mainImpostor.physicsBody;
  93291. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  93292. if (!mainBody || !connectedBody) {
  93293. return;
  93294. }
  93295. var jointData = impostorJoint.joint.jointData;
  93296. var options = jointData.nativeParams || {};
  93297. var type;
  93298. var nativeJointData = {
  93299. body1: mainBody,
  93300. body2: connectedBody,
  93301. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  93302. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  93303. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  93304. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  93305. min: options.min,
  93306. max: options.max,
  93307. collision: options.collision || jointData.collision,
  93308. spring: options.spring,
  93309. //supporting older version of Oimo
  93310. world: this.world
  93311. };
  93312. switch (impostorJoint.joint.type) {
  93313. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  93314. type = "jointBall";
  93315. break;
  93316. case BABYLON.PhysicsJoint.SpringJoint:
  93317. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  93318. var springData = jointData;
  93319. nativeJointData.min = springData.length || nativeJointData.min;
  93320. //Max should also be set, just make sure it is at least min
  93321. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  93322. case BABYLON.PhysicsJoint.DistanceJoint:
  93323. type = "jointDistance";
  93324. nativeJointData.max = jointData.maxDistance;
  93325. break;
  93326. case BABYLON.PhysicsJoint.PrismaticJoint:
  93327. type = "jointPrisme";
  93328. break;
  93329. case BABYLON.PhysicsJoint.SliderJoint:
  93330. type = "jointSlide";
  93331. break;
  93332. case BABYLON.PhysicsJoint.WheelJoint:
  93333. type = "jointWheel";
  93334. break;
  93335. case BABYLON.PhysicsJoint.HingeJoint:
  93336. default:
  93337. type = "jointHinge";
  93338. break;
  93339. }
  93340. nativeJointData.type = type;
  93341. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  93342. };
  93343. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  93344. //Bug in Oimo prevents us from disposing a joint in the playground
  93345. //joint.joint.physicsJoint.dispose();
  93346. //So we will bruteforce it!
  93347. try {
  93348. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  93349. }
  93350. catch (e) {
  93351. BABYLON.Tools.Warn(e);
  93352. }
  93353. };
  93354. OimoJSPlugin.prototype.isSupported = function () {
  93355. return this.BJSOIMO !== undefined;
  93356. };
  93357. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  93358. if (!impostor.physicsBody.sleeping) {
  93359. //TODO check that
  93360. /*if (impostor.physicsBody.shapes.next) {
  93361. var parentShape = this._getLastShape(impostor.physicsBody);
  93362. impostor.object.position.copyFrom(parentShape.position);
  93363. console.log(parentShape.position);
  93364. } else {*/
  93365. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  93366. //}
  93367. if (impostor.object.rotationQuaternion) {
  93368. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  93369. }
  93370. }
  93371. };
  93372. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  93373. var body = impostor.physicsBody;
  93374. body.position.copy(newPosition);
  93375. body.orientation.copy(newRotation);
  93376. body.syncShapes();
  93377. body.awake();
  93378. };
  93379. /*private _getLastShape(body: any): any {
  93380. var lastShape = body.shapes;
  93381. while (lastShape.next) {
  93382. lastShape = lastShape.next;
  93383. }
  93384. return lastShape;
  93385. }*/
  93386. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  93387. impostor.physicsBody.linearVelocity.copy(velocity);
  93388. };
  93389. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  93390. impostor.physicsBody.angularVelocity.copy(velocity);
  93391. };
  93392. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  93393. var v = impostor.physicsBody.linearVelocity;
  93394. if (!v) {
  93395. return null;
  93396. }
  93397. return new BABYLON.Vector3(v.x, v.y, v.z);
  93398. };
  93399. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  93400. var v = impostor.physicsBody.angularVelocity;
  93401. if (!v) {
  93402. return null;
  93403. }
  93404. return new BABYLON.Vector3(v.x, v.y, v.z);
  93405. };
  93406. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  93407. var staticBody = mass === 0;
  93408. //this will actually set the body's density and not its mass.
  93409. //But this is how oimo treats the mass variable.
  93410. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  93411. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  93412. };
  93413. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  93414. return impostor.physicsBody.shapes.density;
  93415. };
  93416. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  93417. return impostor.physicsBody.shapes.friction;
  93418. };
  93419. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  93420. impostor.physicsBody.shapes.friction = friction;
  93421. };
  93422. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  93423. return impostor.physicsBody.shapes.restitution;
  93424. };
  93425. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  93426. impostor.physicsBody.shapes.restitution = restitution;
  93427. };
  93428. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  93429. impostor.physicsBody.sleep();
  93430. };
  93431. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  93432. impostor.physicsBody.awake();
  93433. };
  93434. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  93435. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  93436. if (minDistance !== void 0) {
  93437. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  93438. }
  93439. };
  93440. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  93441. //TODO separate rotational and transational motors.
  93442. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93443. if (motor) {
  93444. motor.setMotor(speed, maxForce);
  93445. }
  93446. };
  93447. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  93448. //TODO separate rotational and transational motors.
  93449. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  93450. if (motor) {
  93451. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  93452. }
  93453. };
  93454. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  93455. var body = impostor.physicsBody;
  93456. mesh.position.x = body.position.x;
  93457. mesh.position.y = body.position.y;
  93458. mesh.position.z = body.position.z;
  93459. if (mesh.rotationQuaternion) {
  93460. mesh.rotationQuaternion.x = body.orientation.x;
  93461. mesh.rotationQuaternion.y = body.orientation.y;
  93462. mesh.rotationQuaternion.z = body.orientation.z;
  93463. mesh.rotationQuaternion.w = body.orientation.s;
  93464. }
  93465. };
  93466. OimoJSPlugin.prototype.getRadius = function (impostor) {
  93467. return impostor.physicsBody.shapes.radius;
  93468. };
  93469. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  93470. var shape = impostor.physicsBody.shapes;
  93471. result.x = shape.halfWidth * 2;
  93472. result.y = shape.halfHeight * 2;
  93473. result.z = shape.halfDepth * 2;
  93474. };
  93475. OimoJSPlugin.prototype.dispose = function () {
  93476. this.world.clear();
  93477. };
  93478. return OimoJSPlugin;
  93479. }());
  93480. BABYLON.OimoJSPlugin = OimoJSPlugin;
  93481. })(BABYLON || (BABYLON = {}));
  93482. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  93483. var BABYLON;
  93484. (function (BABYLON) {
  93485. /**
  93486. * Gets the current physics engine
  93487. * @returns a IPhysicsEngine or null if none attached
  93488. */
  93489. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  93490. return this._physicsEngine;
  93491. };
  93492. /**
  93493. * Enables physics to the current scene
  93494. * @param gravity defines the scene's gravity for the physics engine
  93495. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  93496. * @return a boolean indicating if the physics engine was initialized
  93497. */
  93498. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  93499. if (gravity === void 0) { gravity = null; }
  93500. if (this._physicsEngine) {
  93501. return true;
  93502. }
  93503. // Register the component to the scene
  93504. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  93505. if (!component) {
  93506. component = new PhysicsEngineSceneComponent(this);
  93507. this._addComponent(component);
  93508. }
  93509. try {
  93510. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  93511. return true;
  93512. }
  93513. catch (e) {
  93514. BABYLON.Tools.Error(e.message);
  93515. return false;
  93516. }
  93517. };
  93518. /**
  93519. * Disables and disposes the physics engine associated with the scene
  93520. */
  93521. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  93522. if (!this._physicsEngine) {
  93523. return;
  93524. }
  93525. this._physicsEngine.dispose();
  93526. this._physicsEngine = null;
  93527. };
  93528. /**
  93529. * Gets a boolean indicating if there is an active physics engine
  93530. * @returns a boolean indicating if there is an active physics engine
  93531. */
  93532. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  93533. return this._physicsEngine !== undefined;
  93534. };
  93535. /**
  93536. * Deletes a physics compound impostor
  93537. * @param compound defines the compound to delete
  93538. */
  93539. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  93540. var mesh = compound.parts[0].mesh;
  93541. if (mesh.physicsImpostor) {
  93542. mesh.physicsImpostor.dispose( /*true*/);
  93543. mesh.physicsImpostor = null;
  93544. }
  93545. };
  93546. /** @hidden */
  93547. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  93548. if (this._physicsEngine) {
  93549. this.onBeforePhysicsObservable.notifyObservers(this);
  93550. this._physicsEngine._step(step / 1000);
  93551. this.onAfterPhysicsObservable.notifyObservers(this);
  93552. }
  93553. };
  93554. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  93555. get: function () {
  93556. return this._physicsImpostor;
  93557. },
  93558. set: function (value) {
  93559. var _this = this;
  93560. if (this._physicsImpostor === value) {
  93561. return;
  93562. }
  93563. if (this._disposePhysicsObserver) {
  93564. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  93565. }
  93566. this._physicsImpostor = value;
  93567. if (value) {
  93568. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  93569. // Physics
  93570. if (_this.physicsImpostor) {
  93571. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  93572. _this.physicsImpostor = null;
  93573. }
  93574. });
  93575. }
  93576. },
  93577. enumerable: true,
  93578. configurable: true
  93579. });
  93580. /**
  93581. * Gets the current physics impostor
  93582. * @see http://doc.babylonjs.com/features/physics_engine
  93583. * @returns a physics impostor or null
  93584. */
  93585. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  93586. return this.physicsImpostor;
  93587. };
  93588. /**
  93589. * Apply a physic impulse to the mesh
  93590. * @param force defines the force to apply
  93591. * @param contactPoint defines where to apply the force
  93592. * @returns the current mesh
  93593. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93594. */
  93595. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  93596. if (!this.physicsImpostor) {
  93597. return this;
  93598. }
  93599. this.physicsImpostor.applyImpulse(force, contactPoint);
  93600. return this;
  93601. };
  93602. /**
  93603. * Creates a physic joint between two meshes
  93604. * @param otherMesh defines the other mesh to use
  93605. * @param pivot1 defines the pivot to use on this mesh
  93606. * @param pivot2 defines the pivot to use on the other mesh
  93607. * @param options defines additional options (can be plugin dependent)
  93608. * @returns the current mesh
  93609. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  93610. */
  93611. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  93612. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  93613. return this;
  93614. }
  93615. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  93616. mainPivot: pivot1,
  93617. connectedPivot: pivot2,
  93618. nativeParams: options
  93619. });
  93620. return this;
  93621. };
  93622. /**
  93623. * Defines the physics engine scene component responsible to manage a physics engine
  93624. */
  93625. var PhysicsEngineSceneComponent = /** @class */ (function () {
  93626. /**
  93627. * Creates a new instance of the component for the given scene
  93628. * @param scene Defines the scene to register the component in
  93629. */
  93630. function PhysicsEngineSceneComponent(scene) {
  93631. var _this = this;
  93632. /**
  93633. * The component name helpful to identify the component in the list of scene components.
  93634. */
  93635. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  93636. this.scene = scene;
  93637. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  93638. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  93639. // Replace the function used to get the deterministic frame time
  93640. this.scene.getDeterministicFrameTime = function () {
  93641. if (_this.scene._physicsEngine) {
  93642. return _this.scene._physicsEngine.getTimeStep() * 1000;
  93643. }
  93644. return 1000.0 / 60.0;
  93645. };
  93646. }
  93647. /**
  93648. * Registers the component in a given scene
  93649. */
  93650. PhysicsEngineSceneComponent.prototype.register = function () {
  93651. };
  93652. /**
  93653. * Rebuilds the elements related to this component in case of
  93654. * context lost for instance.
  93655. */
  93656. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  93657. // Nothing to do for this component
  93658. };
  93659. /**
  93660. * Disposes the component and the associated ressources
  93661. */
  93662. PhysicsEngineSceneComponent.prototype.dispose = function () {
  93663. this.scene.onBeforePhysicsObservable.clear();
  93664. this.scene.onAfterPhysicsObservable.clear();
  93665. if (this.scene._physicsEngine) {
  93666. this.scene.disablePhysicsEngine();
  93667. }
  93668. };
  93669. return PhysicsEngineSceneComponent;
  93670. }());
  93671. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  93672. })(BABYLON || (BABYLON = {}));
  93673. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  93674. var BABYLON;
  93675. (function (BABYLON) {
  93676. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  93677. // All values and structures referenced from:
  93678. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  93679. var DDS_MAGIC = 0x20534444;
  93680. var
  93681. //DDSD_CAPS = 0x1,
  93682. //DDSD_HEIGHT = 0x2,
  93683. //DDSD_WIDTH = 0x4,
  93684. //DDSD_PITCH = 0x8,
  93685. //DDSD_PIXELFORMAT = 0x1000,
  93686. DDSD_MIPMAPCOUNT = 0x20000;
  93687. //DDSD_LINEARSIZE = 0x80000,
  93688. //DDSD_DEPTH = 0x800000;
  93689. // var DDSCAPS_COMPLEX = 0x8,
  93690. // DDSCAPS_MIPMAP = 0x400000,
  93691. // DDSCAPS_TEXTURE = 0x1000;
  93692. var DDSCAPS2_CUBEMAP = 0x200;
  93693. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  93694. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  93695. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  93696. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  93697. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  93698. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  93699. // DDSCAPS2_VOLUME = 0x200000;
  93700. var
  93701. //DDPF_ALPHAPIXELS = 0x1,
  93702. //DDPF_ALPHA = 0x2,
  93703. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  93704. //DDPF_YUV = 0x200,
  93705. DDPF_LUMINANCE = 0x20000;
  93706. function FourCCToInt32(value) {
  93707. return value.charCodeAt(0) +
  93708. (value.charCodeAt(1) << 8) +
  93709. (value.charCodeAt(2) << 16) +
  93710. (value.charCodeAt(3) << 24);
  93711. }
  93712. function Int32ToFourCC(value) {
  93713. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  93714. }
  93715. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  93716. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  93717. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  93718. var FOURCC_DX10 = FourCCToInt32("DX10");
  93719. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  93720. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  93721. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  93722. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  93723. var headerLengthInt = 31; // The header length in 32 bit ints
  93724. // Offsets into the header array
  93725. var off_magic = 0;
  93726. var off_size = 1;
  93727. var off_flags = 2;
  93728. var off_height = 3;
  93729. var off_width = 4;
  93730. var off_mipmapCount = 7;
  93731. var off_pfFlags = 20;
  93732. var off_pfFourCC = 21;
  93733. var off_RGBbpp = 22;
  93734. var off_RMask = 23;
  93735. var off_GMask = 24;
  93736. var off_BMask = 25;
  93737. var off_AMask = 26;
  93738. // var off_caps1 = 27;
  93739. var off_caps2 = 28;
  93740. // var off_caps3 = 29;
  93741. // var off_caps4 = 30;
  93742. var off_dxgiFormat = 32;
  93743. ;
  93744. var DDSTools = /** @class */ (function () {
  93745. function DDSTools() {
  93746. }
  93747. DDSTools.GetDDSInfo = function (arrayBuffer) {
  93748. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93749. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  93750. var mipmapCount = 1;
  93751. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  93752. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93753. }
  93754. var fourCC = header[off_pfFourCC];
  93755. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  93756. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93757. switch (fourCC) {
  93758. case FOURCC_D3DFMT_R16G16B16A16F:
  93759. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93760. break;
  93761. case FOURCC_D3DFMT_R32G32B32A32F:
  93762. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93763. break;
  93764. case FOURCC_DX10:
  93765. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  93766. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93767. break;
  93768. }
  93769. }
  93770. return {
  93771. width: header[off_width],
  93772. height: header[off_height],
  93773. mipmapCount: mipmapCount,
  93774. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  93775. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  93776. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  93777. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  93778. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  93779. dxgiFormat: dxgiFormat,
  93780. textureType: textureType
  93781. };
  93782. };
  93783. DDSTools._ToHalfFloat = function (value) {
  93784. if (!DDSTools._FloatView) {
  93785. DDSTools._FloatView = new Float32Array(1);
  93786. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  93787. }
  93788. DDSTools._FloatView[0] = value;
  93789. var x = DDSTools._Int32View[0];
  93790. var bits = (x >> 16) & 0x8000; /* Get the sign */
  93791. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  93792. var e = (x >> 23) & 0xff; /* Using int is faster here */
  93793. /* If zero, or denormal, or exponent underflows too much for a denormal
  93794. * half, return signed zero. */
  93795. if (e < 103) {
  93796. return bits;
  93797. }
  93798. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  93799. if (e > 142) {
  93800. bits |= 0x7c00;
  93801. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  93802. * not Inf, so make sure we set one mantissa bit too. */
  93803. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  93804. return bits;
  93805. }
  93806. /* If exponent underflows but not too much, return a denormal */
  93807. if (e < 113) {
  93808. m |= 0x0800;
  93809. /* Extra rounding may overflow and set mantissa to 0 and exponent
  93810. * to 1, which is OK. */
  93811. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  93812. return bits;
  93813. }
  93814. bits |= ((e - 112) << 10) | (m >> 1);
  93815. bits += m & 1;
  93816. return bits;
  93817. };
  93818. DDSTools._FromHalfFloat = function (value) {
  93819. var s = (value & 0x8000) >> 15;
  93820. var e = (value & 0x7C00) >> 10;
  93821. var f = value & 0x03FF;
  93822. if (e === 0) {
  93823. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  93824. }
  93825. else if (e == 0x1F) {
  93826. return f ? NaN : ((s ? -1 : 1) * Infinity);
  93827. }
  93828. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  93829. };
  93830. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93831. var destArray = new Float32Array(dataLength);
  93832. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93833. var index = 0;
  93834. for (var y = 0; y < height; y++) {
  93835. for (var x = 0; x < width; x++) {
  93836. var srcPos = (x + y * width) * 4;
  93837. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  93838. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  93839. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  93840. if (DDSTools.StoreLODInAlphaChannel) {
  93841. destArray[index + 3] = lod;
  93842. }
  93843. else {
  93844. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  93845. }
  93846. index += 4;
  93847. }
  93848. }
  93849. return destArray;
  93850. };
  93851. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93852. if (DDSTools.StoreLODInAlphaChannel) {
  93853. var destArray = new Uint16Array(dataLength);
  93854. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93855. var index = 0;
  93856. for (var y = 0; y < height; y++) {
  93857. for (var x = 0; x < width; x++) {
  93858. var srcPos = (x + y * width) * 4;
  93859. destArray[index] = srcData[srcPos];
  93860. destArray[index + 1] = srcData[srcPos + 1];
  93861. destArray[index + 2] = srcData[srcPos + 2];
  93862. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  93863. index += 4;
  93864. }
  93865. }
  93866. return destArray;
  93867. }
  93868. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  93869. };
  93870. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93871. if (DDSTools.StoreLODInAlphaChannel) {
  93872. var destArray = new Float32Array(dataLength);
  93873. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93874. var index = 0;
  93875. for (var y = 0; y < height; y++) {
  93876. for (var x = 0; x < width; x++) {
  93877. var srcPos = (x + y * width) * 4;
  93878. destArray[index] = srcData[srcPos];
  93879. destArray[index + 1] = srcData[srcPos + 1];
  93880. destArray[index + 2] = srcData[srcPos + 2];
  93881. destArray[index + 3] = lod;
  93882. index += 4;
  93883. }
  93884. }
  93885. return destArray;
  93886. }
  93887. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  93888. };
  93889. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93890. var destArray = new Uint8Array(dataLength);
  93891. var srcData = new Float32Array(arrayBuffer, dataOffset);
  93892. var index = 0;
  93893. for (var y = 0; y < height; y++) {
  93894. for (var x = 0; x < width; x++) {
  93895. var srcPos = (x + y * width) * 4;
  93896. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  93897. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  93898. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  93899. if (DDSTools.StoreLODInAlphaChannel) {
  93900. destArray[index + 3] = lod;
  93901. }
  93902. else {
  93903. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  93904. }
  93905. index += 4;
  93906. }
  93907. }
  93908. return destArray;
  93909. };
  93910. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  93911. var destArray = new Uint8Array(dataLength);
  93912. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  93913. var index = 0;
  93914. for (var y = 0; y < height; y++) {
  93915. for (var x = 0; x < width; x++) {
  93916. var srcPos = (x + y * width) * 4;
  93917. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  93918. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  93919. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  93920. if (DDSTools.StoreLODInAlphaChannel) {
  93921. destArray[index + 3] = lod;
  93922. }
  93923. else {
  93924. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  93925. }
  93926. index += 4;
  93927. }
  93928. }
  93929. return destArray;
  93930. };
  93931. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  93932. var byteArray = new Uint8Array(dataLength);
  93933. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93934. var index = 0;
  93935. for (var y = 0; y < height; y++) {
  93936. for (var x = 0; x < width; x++) {
  93937. var srcPos = (x + y * width) * 4;
  93938. byteArray[index] = srcData[srcPos + rOffset];
  93939. byteArray[index + 1] = srcData[srcPos + gOffset];
  93940. byteArray[index + 2] = srcData[srcPos + bOffset];
  93941. byteArray[index + 3] = srcData[srcPos + aOffset];
  93942. index += 4;
  93943. }
  93944. }
  93945. return byteArray;
  93946. };
  93947. DDSTools._ExtractLongWordOrder = function (value) {
  93948. if (value === 0 || value === 255 || value === -16777216) {
  93949. return 0;
  93950. }
  93951. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  93952. };
  93953. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  93954. var byteArray = new Uint8Array(dataLength);
  93955. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93956. var index = 0;
  93957. for (var y = 0; y < height; y++) {
  93958. for (var x = 0; x < width; x++) {
  93959. var srcPos = (x + y * width) * 3;
  93960. byteArray[index] = srcData[srcPos + rOffset];
  93961. byteArray[index + 1] = srcData[srcPos + gOffset];
  93962. byteArray[index + 2] = srcData[srcPos + bOffset];
  93963. index += 3;
  93964. }
  93965. }
  93966. return byteArray;
  93967. };
  93968. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  93969. var byteArray = new Uint8Array(dataLength);
  93970. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  93971. var index = 0;
  93972. for (var y = 0; y < height; y++) {
  93973. for (var x = 0; x < width; x++) {
  93974. var srcPos = (x + y * width);
  93975. byteArray[index] = srcData[srcPos];
  93976. index++;
  93977. }
  93978. }
  93979. return byteArray;
  93980. };
  93981. /**
  93982. * Uploads DDS Levels to a Babylon Texture
  93983. * @hidden
  93984. */
  93985. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  93986. if (lodIndex === void 0) { lodIndex = -1; }
  93987. var sphericalPolynomialFaces = null;
  93988. if (info.sphericalPolynomial) {
  93989. sphericalPolynomialFaces = new Array();
  93990. }
  93991. var ext = engine.getCaps().s3tc;
  93992. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  93993. var fourCC, width, height, dataLength = 0, dataOffset;
  93994. var byteArray, mipmapCount, mip;
  93995. var internalCompressedFormat = 0;
  93996. var blockBytes = 1;
  93997. if (header[off_magic] !== DDS_MAGIC) {
  93998. BABYLON.Tools.Error("Invalid magic number in DDS header");
  93999. return;
  94000. }
  94001. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  94002. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  94003. return;
  94004. }
  94005. if (info.isCompressed && !ext) {
  94006. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  94007. return;
  94008. }
  94009. var bpp = header[off_RGBbpp];
  94010. dataOffset = header[off_size] + 4;
  94011. var computeFormats = false;
  94012. if (info.isFourCC) {
  94013. fourCC = header[off_pfFourCC];
  94014. switch (fourCC) {
  94015. case FOURCC_DXT1:
  94016. blockBytes = 8;
  94017. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  94018. break;
  94019. case FOURCC_DXT3:
  94020. blockBytes = 16;
  94021. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  94022. break;
  94023. case FOURCC_DXT5:
  94024. blockBytes = 16;
  94025. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  94026. break;
  94027. case FOURCC_D3DFMT_R16G16B16A16F:
  94028. computeFormats = true;
  94029. break;
  94030. case FOURCC_D3DFMT_R32G32B32A32F:
  94031. computeFormats = true;
  94032. break;
  94033. case FOURCC_DX10:
  94034. // There is an additionnal header so dataOffset need to be changed
  94035. dataOffset += 5 * 4; // 5 uints
  94036. var supported = false;
  94037. switch (info.dxgiFormat) {
  94038. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  94039. computeFormats = true;
  94040. supported = true;
  94041. break;
  94042. case DXGI_FORMAT_B8G8R8X8_UNORM:
  94043. info.isRGB = true;
  94044. info.isFourCC = false;
  94045. bpp = 32;
  94046. supported = true;
  94047. break;
  94048. }
  94049. if (supported) {
  94050. break;
  94051. }
  94052. default:
  94053. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  94054. return;
  94055. }
  94056. }
  94057. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  94058. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  94059. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  94060. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  94061. if (computeFormats) {
  94062. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  94063. }
  94064. mipmapCount = 1;
  94065. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  94066. mipmapCount = Math.max(1, header[off_mipmapCount]);
  94067. }
  94068. for (var face = 0; face < faces; face++) {
  94069. width = header[off_width];
  94070. height = header[off_height];
  94071. for (mip = 0; mip < mipmapCount; ++mip) {
  94072. if (lodIndex === -1 || lodIndex === mip) {
  94073. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  94074. var i = (lodIndex === -1) ? mip : 0;
  94075. if (!info.isCompressed && info.isFourCC) {
  94076. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94077. dataLength = width * height * 4;
  94078. var floatArray = null;
  94079. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  94080. if (bpp === 128) {
  94081. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94082. if (sphericalPolynomialFaces && i == 0) {
  94083. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94084. }
  94085. }
  94086. else if (bpp === 64) {
  94087. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94088. if (sphericalPolynomialFaces && i == 0) {
  94089. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94090. }
  94091. }
  94092. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94093. }
  94094. else {
  94095. if (bpp === 128) {
  94096. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94097. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94098. if (sphericalPolynomialFaces && i == 0) {
  94099. sphericalPolynomialFaces.push(floatArray);
  94100. }
  94101. }
  94102. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  94103. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94104. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94105. if (sphericalPolynomialFaces && i == 0) {
  94106. sphericalPolynomialFaces.push(floatArray);
  94107. }
  94108. }
  94109. else { // 64
  94110. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94111. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  94112. if (sphericalPolynomialFaces && i == 0) {
  94113. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  94114. }
  94115. }
  94116. }
  94117. if (floatArray) {
  94118. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  94119. }
  94120. }
  94121. else if (info.isRGB) {
  94122. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94123. if (bpp === 24) {
  94124. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  94125. dataLength = width * height * 3;
  94126. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  94127. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94128. }
  94129. else { // 32
  94130. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94131. dataLength = width * height * 4;
  94132. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  94133. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94134. }
  94135. }
  94136. else if (info.isLuminance) {
  94137. var unpackAlignment = engine._getUnpackAlignement();
  94138. var unpaddedRowSize = width;
  94139. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  94140. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  94141. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  94142. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  94143. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94144. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  94145. }
  94146. else {
  94147. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  94148. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  94149. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94150. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  94151. }
  94152. }
  94153. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  94154. width *= 0.5;
  94155. height *= 0.5;
  94156. width = Math.max(1.0, width);
  94157. height = Math.max(1.0, height);
  94158. }
  94159. if (currentFace !== undefined) {
  94160. // Loading a single face
  94161. break;
  94162. }
  94163. }
  94164. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  94165. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  94166. size: header[off_width],
  94167. right: sphericalPolynomialFaces[0],
  94168. left: sphericalPolynomialFaces[1],
  94169. up: sphericalPolynomialFaces[2],
  94170. down: sphericalPolynomialFaces[3],
  94171. front: sphericalPolynomialFaces[4],
  94172. back: sphericalPolynomialFaces[5],
  94173. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  94174. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  94175. gammaSpace: false,
  94176. });
  94177. }
  94178. else {
  94179. info.sphericalPolynomial = undefined;
  94180. }
  94181. };
  94182. DDSTools.StoreLODInAlphaChannel = false;
  94183. return DDSTools;
  94184. }());
  94185. BABYLON.DDSTools = DDSTools;
  94186. })(BABYLON || (BABYLON = {}));
  94187. //# sourceMappingURL=babylon.dds.js.map
  94188. var BABYLON;
  94189. (function (BABYLON) {
  94190. /**
  94191. * Implementation of the DDS Texture Loader.
  94192. */
  94193. var DDSTextureLoader = /** @class */ (function () {
  94194. function DDSTextureLoader() {
  94195. /**
  94196. * Defines wether the loader supports cascade loading the different faces.
  94197. */
  94198. this.supportCascades = true;
  94199. }
  94200. /**
  94201. * This returns if the loader support the current file information.
  94202. * @param extension defines the file extension of the file being loaded
  94203. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94204. * @param fallback defines the fallback internal texture if any
  94205. * @param isBase64 defines whether the texture is encoded as a base64
  94206. * @param isBuffer defines whether the texture data are stored as a buffer
  94207. * @returns true if the loader can load the specified file
  94208. */
  94209. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94210. return extension.indexOf(".dds") === 0;
  94211. };
  94212. /**
  94213. * Transform the url before loading if required.
  94214. * @param rootUrl the url of the texture
  94215. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94216. * @returns the transformed texture
  94217. */
  94218. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94219. return rootUrl;
  94220. };
  94221. /**
  94222. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94223. * @param rootUrl the url of the texture
  94224. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94225. * @returns the fallback texture
  94226. */
  94227. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94228. return null;
  94229. };
  94230. /**
  94231. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94232. * @param data contains the texture data
  94233. * @param texture defines the BabylonJS internal texture
  94234. * @param createPolynomials will be true if polynomials have been requested
  94235. * @param onLoad defines the callback to trigger once the texture is ready
  94236. * @param onError defines the callback to trigger in case of error
  94237. */
  94238. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  94239. var engine = texture.getEngine();
  94240. var info;
  94241. var loadMipmap = false;
  94242. if (Array.isArray(imgs)) {
  94243. for (var index = 0; index < imgs.length; index++) {
  94244. var data_1 = imgs[index];
  94245. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  94246. texture.width = info.width;
  94247. texture.height = info.height;
  94248. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94249. engine._unpackFlipY(info.isCompressed);
  94250. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  94251. if (!info.isFourCC && info.mipmapCount === 1) {
  94252. engine.generateMipMapsForCubemap(texture);
  94253. }
  94254. }
  94255. }
  94256. else {
  94257. var data = imgs;
  94258. info = BABYLON.DDSTools.GetDDSInfo(data);
  94259. texture.width = info.width;
  94260. texture.height = info.height;
  94261. if (createPolynomials) {
  94262. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  94263. }
  94264. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  94265. engine._unpackFlipY(info.isCompressed);
  94266. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  94267. if (!info.isFourCC && info.mipmapCount === 1) {
  94268. engine.generateMipMapsForCubemap(texture);
  94269. }
  94270. }
  94271. engine._setCubeMapTextureParams(loadMipmap);
  94272. texture.isReady = true;
  94273. if (onLoad) {
  94274. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  94275. }
  94276. };
  94277. /**
  94278. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94279. * @param data contains the texture data
  94280. * @param texture defines the BabylonJS internal texture
  94281. * @param callback defines the method to call once ready to upload
  94282. */
  94283. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  94284. var info = BABYLON.DDSTools.GetDDSInfo(data);
  94285. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  94286. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  94287. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  94288. });
  94289. };
  94290. return DDSTextureLoader;
  94291. }());
  94292. // Register the loader.
  94293. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  94294. })(BABYLON || (BABYLON = {}));
  94295. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  94296. var BABYLON;
  94297. (function (BABYLON) {
  94298. /*
  94299. * Based on jsTGALoader - Javascript loader for TGA file
  94300. * By Vincent Thibault
  94301. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  94302. */
  94303. var TGATools = /** @class */ (function () {
  94304. function TGATools() {
  94305. }
  94306. TGATools.GetTGAHeader = function (data) {
  94307. var offset = 0;
  94308. var header = {
  94309. id_length: data[offset++],
  94310. colormap_type: data[offset++],
  94311. image_type: data[offset++],
  94312. colormap_index: data[offset++] | data[offset++] << 8,
  94313. colormap_length: data[offset++] | data[offset++] << 8,
  94314. colormap_size: data[offset++],
  94315. origin: [
  94316. data[offset++] | data[offset++] << 8,
  94317. data[offset++] | data[offset++] << 8
  94318. ],
  94319. width: data[offset++] | data[offset++] << 8,
  94320. height: data[offset++] | data[offset++] << 8,
  94321. pixel_size: data[offset++],
  94322. flags: data[offset++]
  94323. };
  94324. return header;
  94325. };
  94326. /**
  94327. * Uploads TGA content to a Babylon Texture
  94328. * @hidden
  94329. */
  94330. TGATools.UploadContent = function (texture, data) {
  94331. // Not enough data to contain header ?
  94332. if (data.length < 19) {
  94333. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  94334. return;
  94335. }
  94336. // Read Header
  94337. var offset = 18;
  94338. var header = TGATools.GetTGAHeader(data);
  94339. // Assume it's a valid Targa file.
  94340. if (header.id_length + offset > data.length) {
  94341. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  94342. return;
  94343. }
  94344. // Skip not needed data
  94345. offset += header.id_length;
  94346. var use_rle = false;
  94347. var use_pal = false;
  94348. var use_grey = false;
  94349. // Get some informations.
  94350. switch (header.image_type) {
  94351. case TGATools._TYPE_RLE_INDEXED:
  94352. use_rle = true;
  94353. case TGATools._TYPE_INDEXED:
  94354. use_pal = true;
  94355. break;
  94356. case TGATools._TYPE_RLE_RGB:
  94357. use_rle = true;
  94358. case TGATools._TYPE_RGB:
  94359. // use_rgb = true;
  94360. break;
  94361. case TGATools._TYPE_RLE_GREY:
  94362. use_rle = true;
  94363. case TGATools._TYPE_GREY:
  94364. use_grey = true;
  94365. break;
  94366. }
  94367. var pixel_data;
  94368. // var numAlphaBits = header.flags & 0xf;
  94369. var pixel_size = header.pixel_size >> 3;
  94370. var pixel_total = header.width * header.height * pixel_size;
  94371. // Read palettes
  94372. var palettes;
  94373. if (use_pal) {
  94374. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  94375. }
  94376. // Read LRE
  94377. if (use_rle) {
  94378. pixel_data = new Uint8Array(pixel_total);
  94379. var c, count, i;
  94380. var localOffset = 0;
  94381. var pixels = new Uint8Array(pixel_size);
  94382. while (offset < pixel_total && localOffset < pixel_total) {
  94383. c = data[offset++];
  94384. count = (c & 0x7f) + 1;
  94385. // RLE pixels
  94386. if (c & 0x80) {
  94387. // Bind pixel tmp array
  94388. for (i = 0; i < pixel_size; ++i) {
  94389. pixels[i] = data[offset++];
  94390. }
  94391. // Copy pixel array
  94392. for (i = 0; i < count; ++i) {
  94393. pixel_data.set(pixels, localOffset + i * pixel_size);
  94394. }
  94395. localOffset += pixel_size * count;
  94396. }
  94397. // Raw pixels
  94398. else {
  94399. count *= pixel_size;
  94400. for (i = 0; i < count; ++i) {
  94401. pixel_data[localOffset + i] = data[offset++];
  94402. }
  94403. localOffset += count;
  94404. }
  94405. }
  94406. }
  94407. // RAW Pixels
  94408. else {
  94409. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  94410. }
  94411. // Load to texture
  94412. var x_start, y_start, x_step, y_step, y_end, x_end;
  94413. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  94414. default:
  94415. case TGATools._ORIGIN_UL:
  94416. x_start = 0;
  94417. x_step = 1;
  94418. x_end = header.width;
  94419. y_start = 0;
  94420. y_step = 1;
  94421. y_end = header.height;
  94422. break;
  94423. case TGATools._ORIGIN_BL:
  94424. x_start = 0;
  94425. x_step = 1;
  94426. x_end = header.width;
  94427. y_start = header.height - 1;
  94428. y_step = -1;
  94429. y_end = -1;
  94430. break;
  94431. case TGATools._ORIGIN_UR:
  94432. x_start = header.width - 1;
  94433. x_step = -1;
  94434. x_end = -1;
  94435. y_start = 0;
  94436. y_step = 1;
  94437. y_end = header.height;
  94438. break;
  94439. case TGATools._ORIGIN_BR:
  94440. x_start = header.width - 1;
  94441. x_step = -1;
  94442. x_end = -1;
  94443. y_start = header.height - 1;
  94444. y_step = -1;
  94445. y_end = -1;
  94446. break;
  94447. }
  94448. // Load the specify method
  94449. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  94450. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  94451. var engine = texture.getEngine();
  94452. engine._uploadDataToTextureDirectly(texture, imageData);
  94453. };
  94454. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94455. var image = pixel_data, colormap = palettes;
  94456. var width = header.width, height = header.height;
  94457. var color, i = 0, x, y;
  94458. var imageData = new Uint8Array(width * height * 4);
  94459. for (y = y_start; y !== y_end; y += y_step) {
  94460. for (x = x_start; x !== x_end; x += x_step, i++) {
  94461. color = image[i];
  94462. imageData[(x + width * y) * 4 + 3] = 255;
  94463. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  94464. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  94465. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  94466. }
  94467. }
  94468. return imageData;
  94469. };
  94470. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94471. var image = pixel_data;
  94472. var width = header.width, height = header.height;
  94473. var color, i = 0, x, y;
  94474. var imageData = new Uint8Array(width * height * 4);
  94475. for (y = y_start; y !== y_end; y += y_step) {
  94476. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94477. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  94478. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  94479. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  94480. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  94481. imageData[(x + width * y) * 4 + 0] = r;
  94482. imageData[(x + width * y) * 4 + 1] = g;
  94483. imageData[(x + width * y) * 4 + 2] = b;
  94484. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  94485. }
  94486. }
  94487. return imageData;
  94488. };
  94489. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94490. var image = pixel_data;
  94491. var width = header.width, height = header.height;
  94492. var i = 0, x, y;
  94493. var imageData = new Uint8Array(width * height * 4);
  94494. for (y = y_start; y !== y_end; y += y_step) {
  94495. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  94496. imageData[(x + width * y) * 4 + 3] = 255;
  94497. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94498. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94499. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94500. }
  94501. }
  94502. return imageData;
  94503. };
  94504. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94505. var image = pixel_data;
  94506. var width = header.width, height = header.height;
  94507. var i = 0, x, y;
  94508. var imageData = new Uint8Array(width * height * 4);
  94509. for (y = y_start; y !== y_end; y += y_step) {
  94510. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  94511. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94512. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  94513. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  94514. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  94515. }
  94516. }
  94517. return imageData;
  94518. };
  94519. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94520. var image = pixel_data;
  94521. var width = header.width, height = header.height;
  94522. var color, i = 0, x, y;
  94523. var imageData = new Uint8Array(width * height * 4);
  94524. for (y = y_start; y !== y_end; y += y_step) {
  94525. for (x = x_start; x !== x_end; x += x_step, i++) {
  94526. color = image[i];
  94527. imageData[(x + width * y) * 4 + 0] = color;
  94528. imageData[(x + width * y) * 4 + 1] = color;
  94529. imageData[(x + width * y) * 4 + 2] = color;
  94530. imageData[(x + width * y) * 4 + 3] = 255;
  94531. }
  94532. }
  94533. return imageData;
  94534. };
  94535. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  94536. var image = pixel_data;
  94537. var width = header.width, height = header.height;
  94538. var i = 0, x, y;
  94539. var imageData = new Uint8Array(width * height * 4);
  94540. for (y = y_start; y !== y_end; y += y_step) {
  94541. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  94542. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  94543. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  94544. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  94545. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  94546. }
  94547. }
  94548. return imageData;
  94549. };
  94550. //private static _TYPE_NO_DATA = 0;
  94551. TGATools._TYPE_INDEXED = 1;
  94552. TGATools._TYPE_RGB = 2;
  94553. TGATools._TYPE_GREY = 3;
  94554. TGATools._TYPE_RLE_INDEXED = 9;
  94555. TGATools._TYPE_RLE_RGB = 10;
  94556. TGATools._TYPE_RLE_GREY = 11;
  94557. TGATools._ORIGIN_MASK = 0x30;
  94558. TGATools._ORIGIN_SHIFT = 0x04;
  94559. TGATools._ORIGIN_BL = 0x00;
  94560. TGATools._ORIGIN_BR = 0x01;
  94561. TGATools._ORIGIN_UL = 0x02;
  94562. TGATools._ORIGIN_UR = 0x03;
  94563. return TGATools;
  94564. }());
  94565. BABYLON.TGATools = TGATools;
  94566. })(BABYLON || (BABYLON = {}));
  94567. //# sourceMappingURL=babylon.tga.js.map
  94568. var BABYLON;
  94569. (function (BABYLON) {
  94570. /**
  94571. * Implementation of the TGA Texture Loader.
  94572. */
  94573. var TGATextureLoader = /** @class */ (function () {
  94574. function TGATextureLoader() {
  94575. /**
  94576. * Defines wether the loader supports cascade loading the different faces.
  94577. */
  94578. this.supportCascades = false;
  94579. }
  94580. /**
  94581. * This returns if the loader support the current file information.
  94582. * @param extension defines the file extension of the file being loaded
  94583. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94584. * @param fallback defines the fallback internal texture if any
  94585. * @param isBase64 defines whether the texture is encoded as a base64
  94586. * @param isBuffer defines whether the texture data are stored as a buffer
  94587. * @returns true if the loader can load the specified file
  94588. */
  94589. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94590. return extension.indexOf(".tga") === 0;
  94591. };
  94592. /**
  94593. * Transform the url before loading if required.
  94594. * @param rootUrl the url of the texture
  94595. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94596. * @returns the transformed texture
  94597. */
  94598. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94599. return rootUrl;
  94600. };
  94601. /**
  94602. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94603. * @param rootUrl the url of the texture
  94604. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94605. * @returns the fallback texture
  94606. */
  94607. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94608. return null;
  94609. };
  94610. /**
  94611. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94612. * @param data contains the texture data
  94613. * @param texture defines the BabylonJS internal texture
  94614. * @param createPolynomials will be true if polynomials have been requested
  94615. * @param onLoad defines the callback to trigger once the texture is ready
  94616. * @param onError defines the callback to trigger in case of error
  94617. */
  94618. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94619. throw ".env not supported in Cube.";
  94620. };
  94621. /**
  94622. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94623. * @param data contains the texture data
  94624. * @param texture defines the BabylonJS internal texture
  94625. * @param callback defines the method to call once ready to upload
  94626. */
  94627. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  94628. var uintData = new Uint8Array(data);
  94629. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  94630. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  94631. BABYLON.TGATools.UploadContent(texture, uintData);
  94632. });
  94633. };
  94634. return TGATextureLoader;
  94635. }());
  94636. // Register the loader.
  94637. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  94638. })(BABYLON || (BABYLON = {}));
  94639. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  94640. var BABYLON;
  94641. (function (BABYLON) {
  94642. /**
  94643. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  94644. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  94645. */
  94646. var KhronosTextureContainer = /** @class */ (function () {
  94647. /**
  94648. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  94649. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  94650. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  94651. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  94652. */
  94653. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  94654. this.arrayBuffer = arrayBuffer;
  94655. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  94656. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  94657. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  94658. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  94659. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  94660. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  94661. BABYLON.Tools.Error("texture missing KTX identifier");
  94662. return;
  94663. }
  94664. // load the reset of the header in native 32 bit int
  94665. var header = new Int32Array(this.arrayBuffer, 12, 13);
  94666. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  94667. var oppositeEndianess = header[0] === 0x01020304;
  94668. // read all the header elements in order they exist in the file, without modification (sans endainness)
  94669. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  94670. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  94671. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  94672. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  94673. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  94674. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  94675. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  94676. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  94677. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  94678. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  94679. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  94680. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  94681. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  94682. if (this.glType !== 0) {
  94683. BABYLON.Tools.Error("only compressed formats currently supported");
  94684. return;
  94685. }
  94686. else {
  94687. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  94688. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  94689. }
  94690. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  94691. BABYLON.Tools.Error("only 2D textures currently supported");
  94692. return;
  94693. }
  94694. if (this.numberOfArrayElements !== 0) {
  94695. BABYLON.Tools.Error("texture arrays not currently supported");
  94696. return;
  94697. }
  94698. if (this.numberOfFaces !== facesExpected) {
  94699. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  94700. return;
  94701. }
  94702. // we now have a completely validated file, so could use existence of loadType as success
  94703. // would need to make this more elaborate & adjust checks above to support more than one load type
  94704. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  94705. }
  94706. // not as fast hardware based, but will probably never need to use
  94707. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  94708. return ((val & 0xFF) << 24)
  94709. | ((val & 0xFF00) << 8)
  94710. | ((val >> 8) & 0xFF00)
  94711. | ((val >> 24) & 0xFF);
  94712. };
  94713. /**
  94714. * Uploads KTX content to a Babylon Texture.
  94715. * It is assumed that the texture has already been created & is currently bound
  94716. * @hidden
  94717. */
  94718. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  94719. switch (this.loadType) {
  94720. case KhronosTextureContainer.COMPRESSED_2D:
  94721. this._upload2DCompressedLevels(texture, loadMipmaps);
  94722. break;
  94723. case KhronosTextureContainer.TEX_2D:
  94724. case KhronosTextureContainer.COMPRESSED_3D:
  94725. case KhronosTextureContainer.TEX_3D:
  94726. }
  94727. };
  94728. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  94729. // initialize width & height for level 1
  94730. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  94731. var width = this.pixelWidth;
  94732. var height = this.pixelHeight;
  94733. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  94734. for (var level = 0; level < mipmapCount; level++) {
  94735. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  94736. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  94737. for (var face = 0; face < this.numberOfFaces; face++) {
  94738. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  94739. var engine = texture.getEngine();
  94740. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  94741. dataOffset += imageSize; // add size of the image for the next face/mipmap
  94742. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  94743. }
  94744. width = Math.max(1.0, width * 0.5);
  94745. height = Math.max(1.0, height * 0.5);
  94746. }
  94747. };
  94748. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  94749. // load types
  94750. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  94751. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  94752. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  94753. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  94754. return KhronosTextureContainer;
  94755. }());
  94756. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  94757. })(BABYLON || (BABYLON = {}));
  94758. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  94759. var BABYLON;
  94760. (function (BABYLON) {
  94761. /**
  94762. * Implementation of the KTX Texture Loader.
  94763. */
  94764. var KTXTextureLoader = /** @class */ (function () {
  94765. function KTXTextureLoader() {
  94766. /**
  94767. * Defines wether the loader supports cascade loading the different faces.
  94768. */
  94769. this.supportCascades = false;
  94770. }
  94771. /**
  94772. * This returns if the loader support the current file information.
  94773. * @param extension defines the file extension of the file being loaded
  94774. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94775. * @param fallback defines the fallback internal texture if any
  94776. * @param isBase64 defines whether the texture is encoded as a base64
  94777. * @param isBuffer defines whether the texture data are stored as a buffer
  94778. * @returns true if the loader can load the specified file
  94779. */
  94780. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94781. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  94782. return true;
  94783. }
  94784. return false;
  94785. };
  94786. /**
  94787. * Transform the url before loading if required.
  94788. * @param rootUrl the url of the texture
  94789. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94790. * @returns the transformed texture
  94791. */
  94792. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94793. var lastDot = rootUrl.lastIndexOf('.');
  94794. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  94795. };
  94796. /**
  94797. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94798. * @param rootUrl the url of the texture
  94799. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94800. * @returns the fallback texture
  94801. */
  94802. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94803. // remove the format appended to the rootUrl in the original createCubeTexture call.
  94804. var exp = new RegExp("" + textureFormatInUse + "$");
  94805. return rootUrl.replace(exp, "");
  94806. };
  94807. /**
  94808. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94809. * @param data contains the texture data
  94810. * @param texture defines the BabylonJS internal texture
  94811. * @param createPolynomials will be true if polynomials have been requested
  94812. * @param onLoad defines the callback to trigger once the texture is ready
  94813. * @param onError defines the callback to trigger in case of error
  94814. */
  94815. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94816. if (Array.isArray(data)) {
  94817. return;
  94818. }
  94819. var engine = texture.getEngine();
  94820. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  94821. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  94822. engine._unpackFlipY(true);
  94823. ktx.uploadLevels(texture, texture.generateMipMaps);
  94824. texture.width = ktx.pixelWidth;
  94825. texture.height = ktx.pixelHeight;
  94826. engine._setCubeMapTextureParams(loadMipmap);
  94827. texture.isReady = true;
  94828. };
  94829. /**
  94830. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94831. * @param data contains the texture data
  94832. * @param texture defines the BabylonJS internal texture
  94833. * @param callback defines the method to call once ready to upload
  94834. */
  94835. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  94836. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  94837. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  94838. ktx.uploadLevels(texture, texture.generateMipMaps);
  94839. });
  94840. };
  94841. return KTXTextureLoader;
  94842. }());
  94843. // Register the loader.
  94844. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  94845. })(BABYLON || (BABYLON = {}));
  94846. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  94847. var BABYLON;
  94848. (function (BABYLON) {
  94849. /**
  94850. * Sets of helpers addressing the serialization and deserialization of environment texture
  94851. * stored in a BabylonJS env file.
  94852. * Those files are usually stored as .env files.
  94853. */
  94854. var EnvironmentTextureTools = /** @class */ (function () {
  94855. function EnvironmentTextureTools() {
  94856. }
  94857. /**
  94858. * Gets the environment info from an env file.
  94859. * @param data The array buffer containing the .env bytes.
  94860. * @returns the environment file info (the json header) if successfully parsed.
  94861. */
  94862. EnvironmentTextureTools.GetEnvInfo = function (data) {
  94863. var dataView = new DataView(data);
  94864. var pos = 0;
  94865. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  94866. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  94867. BABYLON.Tools.Error('Not a babylon environment map');
  94868. return null;
  94869. }
  94870. }
  94871. // Read json manifest - collect characters up to null terminator
  94872. var manifestString = '';
  94873. var charCode = 0x00;
  94874. while ((charCode = dataView.getUint8(pos++))) {
  94875. manifestString += String.fromCharCode(charCode);
  94876. }
  94877. var manifest = JSON.parse(manifestString);
  94878. if (manifest.specular) {
  94879. // Extend the header with the position of the payload.
  94880. manifest.specular.specularDataPosition = pos;
  94881. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  94882. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  94883. }
  94884. return manifest;
  94885. };
  94886. /**
  94887. * Creates an environment texture from a loaded cube texture.
  94888. * @param texture defines the cube texture to convert in env file
  94889. * @return a promise containing the environment data if succesfull.
  94890. */
  94891. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  94892. var _this = this;
  94893. var internalTexture = texture.getInternalTexture();
  94894. if (!internalTexture) {
  94895. return Promise.reject("The cube texture is invalid.");
  94896. }
  94897. if (!texture._prefiltered) {
  94898. return Promise.reject("The cube texture is invalid (not prefiltered).");
  94899. }
  94900. var engine = internalTexture.getEngine();
  94901. if (engine && engine.premultipliedAlpha) {
  94902. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  94903. }
  94904. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  94905. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  94906. }
  94907. var canvas = engine.getRenderingCanvas();
  94908. if (!canvas) {
  94909. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  94910. }
  94911. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94912. if (!engine.getCaps().textureFloatRender) {
  94913. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94914. if (!engine.getCaps().textureHalfFloatRender) {
  94915. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  94916. }
  94917. }
  94918. var cubeWidth = internalTexture.width;
  94919. var hostingScene = new BABYLON.Scene(engine);
  94920. var specularTextures = {};
  94921. var promises = [];
  94922. // Read and collect all mipmaps data from the cube.
  94923. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  94924. mipmapsCount = Math.round(mipmapsCount);
  94925. var _loop_1 = function (i) {
  94926. var faceWidth = Math.pow(2, mipmapsCount - i);
  94927. var _loop_2 = function (face) {
  94928. var data = texture.readPixels(face, i);
  94929. // Creates a temp texture with the face data.
  94930. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  94931. // And rgbdEncode them.
  94932. var promise = new Promise(function (resolve, reject) {
  94933. 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);
  94934. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94935. rgbdPostProcess.onApply = function (effect) {
  94936. effect._bindTexture("textureSampler", tempTexture);
  94937. };
  94938. // As the process needs to happen on the main canvas, keep track of the current size
  94939. var currentW = engine.getRenderWidth();
  94940. var currentH = engine.getRenderHeight();
  94941. // Set the desired size for the texture
  94942. engine.setSize(faceWidth, faceWidth);
  94943. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  94944. // Reading datas from WebGL
  94945. BABYLON.Tools.ToBlob(canvas, function (blob) {
  94946. var fileReader = new FileReader();
  94947. fileReader.onload = function (event) {
  94948. var arrayBuffer = event.target.result;
  94949. specularTextures[i * 6 + face] = arrayBuffer;
  94950. resolve();
  94951. };
  94952. fileReader.readAsArrayBuffer(blob);
  94953. });
  94954. // Reapply the previous canvas size
  94955. engine.setSize(currentW, currentH);
  94956. });
  94957. });
  94958. promises.push(promise);
  94959. };
  94960. // All faces of the cube.
  94961. for (var face = 0; face < 6; face++) {
  94962. _loop_2(face);
  94963. }
  94964. };
  94965. for (var i = 0; i <= mipmapsCount; i++) {
  94966. _loop_1(i);
  94967. }
  94968. // Once all the textures haves been collected as RGBD stored in PNGs
  94969. return Promise.all(promises).then(function () {
  94970. // We can delete the hosting scene keeping track of all the creation objects
  94971. hostingScene.dispose();
  94972. // Creates the json header for the env texture
  94973. var info = {
  94974. version: 1,
  94975. width: cubeWidth,
  94976. irradiance: _this._CreateEnvTextureIrradiance(texture),
  94977. specular: {
  94978. mipmaps: [],
  94979. lodGenerationScale: texture.lodGenerationScale
  94980. }
  94981. };
  94982. // Sets the specular image data information
  94983. var position = 0;
  94984. for (var i = 0; i <= mipmapsCount; i++) {
  94985. for (var face = 0; face < 6; face++) {
  94986. var byteLength = specularTextures[i * 6 + face].byteLength;
  94987. info.specular.mipmaps.push({
  94988. length: byteLength,
  94989. position: position
  94990. });
  94991. position += byteLength;
  94992. }
  94993. }
  94994. // Encode the JSON as an array buffer
  94995. var infoString = JSON.stringify(info);
  94996. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  94997. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  94998. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  94999. infoView[i] = infoString.charCodeAt(i);
  95000. }
  95001. // Ends up with a null terminator for easier parsing
  95002. infoView[infoString.length] = 0x00;
  95003. // Computes the final required size and creates the storage
  95004. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  95005. var finalBuffer = new ArrayBuffer(totalSize);
  95006. var finalBufferView = new Uint8Array(finalBuffer);
  95007. var dataView = new DataView(finalBuffer);
  95008. // Copy the magic bytes identifying the file in
  95009. var pos = 0;
  95010. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  95011. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  95012. }
  95013. // Add the json info
  95014. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  95015. pos += infoBuffer.byteLength;
  95016. // Finally inserts the texture data
  95017. for (var i = 0; i <= mipmapsCount; i++) {
  95018. for (var face = 0; face < 6; face++) {
  95019. var dataBuffer = specularTextures[i * 6 + face];
  95020. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  95021. pos += dataBuffer.byteLength;
  95022. }
  95023. }
  95024. // Voila
  95025. return finalBuffer;
  95026. });
  95027. };
  95028. /**
  95029. * Creates a JSON representation of the spherical data.
  95030. * @param texture defines the texture containing the polynomials
  95031. * @return the JSON representation of the spherical info
  95032. */
  95033. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  95034. var polynmials = texture.sphericalPolynomial;
  95035. if (polynmials == null) {
  95036. return null;
  95037. }
  95038. return {
  95039. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  95040. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  95041. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  95042. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  95043. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  95044. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  95045. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  95046. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  95047. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  95048. };
  95049. };
  95050. /**
  95051. * Uploads the texture info contained in the env file to the GPU.
  95052. * @param texture defines the internal texture to upload to
  95053. * @param arrayBuffer defines the buffer cotaining the data to load
  95054. * @param info defines the texture info retrieved through the GetEnvInfo method
  95055. * @returns a promise
  95056. */
  95057. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  95058. if (info.version !== 1) {
  95059. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  95060. }
  95061. var specularInfo = info.specular;
  95062. if (!specularInfo) {
  95063. // Nothing else parsed so far
  95064. return Promise.resolve();
  95065. }
  95066. // Double checks the enclosed info
  95067. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  95068. mipmapsCount = Math.round(mipmapsCount) + 1;
  95069. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  95070. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  95071. }
  95072. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  95073. var imageData = new Array(mipmapsCount);
  95074. for (var i = 0; i < mipmapsCount; i++) {
  95075. imageData[i] = new Array(6);
  95076. for (var face = 0; face < 6; face++) {
  95077. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  95078. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  95079. }
  95080. }
  95081. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  95082. };
  95083. /**
  95084. * Uploads the levels of image data to the GPU.
  95085. * @param texture defines the internal texture to upload to
  95086. * @param imageData defines the array buffer views of image data [mipmap][face]
  95087. * @returns a promise
  95088. */
  95089. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  95090. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  95091. throw new Error("Texture size must be a power of two");
  95092. }
  95093. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  95094. // Gets everything ready.
  95095. var engine = texture.getEngine();
  95096. var expandTexture = false;
  95097. var generateNonLODTextures = false;
  95098. var rgbdPostProcess = null;
  95099. var cubeRtt = null;
  95100. var lodTextures = null;
  95101. var caps = engine.getCaps();
  95102. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  95103. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95104. texture.generateMipMaps = true;
  95105. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  95106. // Add extra process if texture lod is not supported
  95107. if (!caps.textureLOD) {
  95108. expandTexture = false;
  95109. generateNonLODTextures = true;
  95110. lodTextures = {};
  95111. }
  95112. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  95113. else if (engine.webGLVersion < 2) {
  95114. expandTexture = false;
  95115. }
  95116. // If half float available we can uncompress the texture
  95117. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  95118. expandTexture = true;
  95119. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95120. }
  95121. // If full float available we can uncompress the texture
  95122. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  95123. expandTexture = true;
  95124. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95125. }
  95126. // Expand the texture if possible
  95127. if (expandTexture) {
  95128. // Simply run through the decode PP
  95129. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  95130. texture._isRGBD = false;
  95131. texture.invertY = false;
  95132. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  95133. generateDepthBuffer: false,
  95134. generateMipMaps: true,
  95135. generateStencilBuffer: false,
  95136. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  95137. type: texture.type,
  95138. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  95139. });
  95140. }
  95141. else {
  95142. texture._isRGBD = true;
  95143. texture.invertY = true;
  95144. // In case of missing support, applies the same patch than DDS files.
  95145. if (generateNonLODTextures) {
  95146. var mipSlices = 3;
  95147. var scale = texture._lodGenerationScale;
  95148. var offset = texture._lodGenerationOffset;
  95149. for (var i = 0; i < mipSlices; i++) {
  95150. //compute LOD from even spacing in smoothness (matching shader calculation)
  95151. var smoothness = i / (mipSlices - 1);
  95152. var roughness = 1 - smoothness;
  95153. var minLODIndex = offset; // roughness = 0
  95154. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  95155. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  95156. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  95157. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  95158. glTextureFromLod.isCube = true;
  95159. glTextureFromLod.invertY = true;
  95160. glTextureFromLod.generateMipMaps = false;
  95161. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  95162. // Wrap in a base texture for easy binding.
  95163. var lodTexture = new BABYLON.BaseTexture(null);
  95164. lodTexture.isCube = true;
  95165. lodTexture._texture = glTextureFromLod;
  95166. lodTextures[mipmapIndex] = lodTexture;
  95167. switch (i) {
  95168. case 0:
  95169. texture._lodTextureLow = lodTexture;
  95170. break;
  95171. case 1:
  95172. texture._lodTextureMid = lodTexture;
  95173. break;
  95174. case 2:
  95175. texture._lodTextureHigh = lodTexture;
  95176. break;
  95177. }
  95178. }
  95179. }
  95180. }
  95181. var promises = [];
  95182. var _loop_3 = function (i) {
  95183. var _loop_4 = function (face) {
  95184. // Constructs an image element from image data
  95185. var bytes = imageData[i][face];
  95186. var blob = new Blob([bytes], { type: 'image/png' });
  95187. var url = URL.createObjectURL(blob);
  95188. var image = new Image();
  95189. image.src = url;
  95190. // Enqueue promise to upload to the texture.
  95191. var promise = new Promise(function (resolve, reject) {
  95192. image.onload = function () {
  95193. if (expandTexture) {
  95194. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  95195. reject(message);
  95196. }, image);
  95197. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  95198. // Uncompress the data to a RTT
  95199. rgbdPostProcess.onApply = function (effect) {
  95200. effect._bindTexture("textureSampler", tempTexture_1);
  95201. effect.setFloat2("scale", 1, 1);
  95202. };
  95203. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  95204. // Cleanup
  95205. engine.restoreDefaultFramebuffer();
  95206. tempTexture_1.dispose();
  95207. window.URL.revokeObjectURL(url);
  95208. resolve();
  95209. });
  95210. }
  95211. else {
  95212. engine._uploadImageToTexture(texture, image, face, i);
  95213. // Upload the face to the non lod texture support
  95214. if (generateNonLODTextures) {
  95215. var lodTexture = lodTextures[i];
  95216. if (lodTexture) {
  95217. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  95218. }
  95219. }
  95220. resolve();
  95221. }
  95222. };
  95223. image.onerror = function (error) {
  95224. reject(error);
  95225. };
  95226. });
  95227. promises.push(promise);
  95228. };
  95229. // All faces
  95230. for (var face = 0; face < 6; face++) {
  95231. _loop_4(face);
  95232. }
  95233. };
  95234. // All mipmaps up to provided number of images
  95235. for (var i = 0; i < imageData.length; i++) {
  95236. _loop_3(i);
  95237. }
  95238. // Fill remaining mipmaps with black textures.
  95239. if (imageData.length < mipmapsCount) {
  95240. var data = void 0;
  95241. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  95242. var dataLength = size * size * 4;
  95243. switch (texture.type) {
  95244. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  95245. data = new Uint8Array(dataLength);
  95246. break;
  95247. }
  95248. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  95249. data = new Uint16Array(dataLength);
  95250. break;
  95251. }
  95252. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  95253. data = new Float32Array(dataLength);
  95254. break;
  95255. }
  95256. }
  95257. for (var i = imageData.length; i < mipmapsCount; i++) {
  95258. for (var face = 0; face < 6; face++) {
  95259. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  95260. }
  95261. }
  95262. }
  95263. // Once all done, finishes the cleanup and return
  95264. return Promise.all(promises).then(function () {
  95265. // Release temp RTT.
  95266. if (cubeRtt) {
  95267. engine._releaseFramebufferObjects(cubeRtt);
  95268. cubeRtt._swapAndDie(texture);
  95269. }
  95270. // Release temp Post Process.
  95271. if (rgbdPostProcess) {
  95272. rgbdPostProcess.dispose();
  95273. }
  95274. // Flag internal texture as ready in case they are in use.
  95275. if (generateNonLODTextures) {
  95276. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  95277. texture._lodTextureHigh._texture.isReady = true;
  95278. }
  95279. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  95280. texture._lodTextureMid._texture.isReady = true;
  95281. }
  95282. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  95283. texture._lodTextureLow._texture.isReady = true;
  95284. }
  95285. }
  95286. });
  95287. };
  95288. /**
  95289. * Uploads spherical polynomials information to the texture.
  95290. * @param texture defines the texture we are trying to upload the information to
  95291. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  95292. */
  95293. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  95294. if (info.version !== 1) {
  95295. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  95296. }
  95297. var irradianceInfo = info.irradiance;
  95298. if (!irradianceInfo) {
  95299. return;
  95300. }
  95301. var sp = new BABYLON.SphericalPolynomial();
  95302. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  95303. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  95304. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  95305. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  95306. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  95307. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  95308. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  95309. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  95310. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  95311. texture._sphericalPolynomial = sp;
  95312. };
  95313. /**
  95314. * Magic number identifying the env file.
  95315. */
  95316. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  95317. return EnvironmentTextureTools;
  95318. }());
  95319. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  95320. })(BABYLON || (BABYLON = {}));
  95321. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  95322. var BABYLON;
  95323. (function (BABYLON) {
  95324. /**
  95325. * Implementation of the ENV Texture Loader.
  95326. */
  95327. var ENVTextureLoader = /** @class */ (function () {
  95328. function ENVTextureLoader() {
  95329. /**
  95330. * Defines wether the loader supports cascade loading the different faces.
  95331. */
  95332. this.supportCascades = false;
  95333. }
  95334. /**
  95335. * This returns if the loader support the current file information.
  95336. * @param extension defines the file extension of the file being loaded
  95337. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95338. * @param fallback defines the fallback internal texture if any
  95339. * @param isBase64 defines whether the texture is encoded as a base64
  95340. * @param isBuffer defines whether the texture data are stored as a buffer
  95341. * @returns true if the loader can load the specified file
  95342. */
  95343. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  95344. return extension.indexOf(".env") === 0;
  95345. };
  95346. /**
  95347. * Transform the url before loading if required.
  95348. * @param rootUrl the url of the texture
  95349. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95350. * @returns the transformed texture
  95351. */
  95352. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  95353. return rootUrl;
  95354. };
  95355. /**
  95356. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  95357. * @param rootUrl the url of the texture
  95358. * @param textureFormatInUse defines the current compressed format in use iun the engine
  95359. * @returns the fallback texture
  95360. */
  95361. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  95362. return null;
  95363. };
  95364. /**
  95365. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  95366. * @param data contains the texture data
  95367. * @param texture defines the BabylonJS internal texture
  95368. * @param createPolynomials will be true if polynomials have been requested
  95369. * @param onLoad defines the callback to trigger once the texture is ready
  95370. * @param onError defines the callback to trigger in case of error
  95371. */
  95372. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  95373. if (Array.isArray(data)) {
  95374. return;
  95375. }
  95376. data = data;
  95377. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  95378. if (info) {
  95379. texture.width = info.width;
  95380. texture.height = info.width;
  95381. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  95382. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  95383. texture.isReady = true;
  95384. if (onLoad) {
  95385. onLoad();
  95386. }
  95387. });
  95388. }
  95389. else if (onError) {
  95390. onError("Can not parse the environment file", null);
  95391. }
  95392. };
  95393. /**
  95394. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  95395. * @param data contains the texture data
  95396. * @param texture defines the BabylonJS internal texture
  95397. * @param callback defines the method to call once ready to upload
  95398. */
  95399. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  95400. throw ".env not supported in 2d.";
  95401. };
  95402. return ENVTextureLoader;
  95403. }());
  95404. // Register the loader.
  95405. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  95406. })(BABYLON || (BABYLON = {}));
  95407. //# sourceMappingURL=babylon.envTextureLoader.js.map
  95408. var BABYLON;
  95409. (function (BABYLON) {
  95410. /**
  95411. * Renders a layer on top of an existing scene
  95412. */
  95413. var UtilityLayerRenderer = /** @class */ (function () {
  95414. /**
  95415. * Instantiates a UtilityLayerRenderer
  95416. * @param originalScene the original scene that will be rendered on top of
  95417. */
  95418. function UtilityLayerRenderer(
  95419. /** the original scene that will be rendered on top of */
  95420. originalScene) {
  95421. var _this = this;
  95422. this.originalScene = originalScene;
  95423. this._pointerCaptures = {};
  95424. this._lastPointerEvents = {};
  95425. /**
  95426. * If the utility layer should automatically be rendered on top of existing scene
  95427. */
  95428. this.shouldRender = true;
  95429. /**
  95430. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  95431. */
  95432. this.onlyCheckPointerDownEvents = true;
  95433. /**
  95434. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  95435. */
  95436. this.processAllEvents = false;
  95437. /**
  95438. * Observable raised when the pointer move from the utility layer scene to the main scene
  95439. */
  95440. this.onPointerOutObservable = new BABYLON.Observable();
  95441. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  95442. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  95443. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  95444. this.utilityLayerScene._allowPostProcessClearColor = false;
  95445. originalScene.getEngine().scenes.pop();
  95446. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  95447. this.utilityLayerScene.detachControl();
  95448. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  95449. if (!_this.processAllEvents) {
  95450. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  95451. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  95452. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  95453. return;
  95454. }
  95455. }
  95456. var pointerEvent = (prePointerInfo.event);
  95457. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  95458. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95459. return;
  95460. }
  95461. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  95462. if (!prePointerInfo.ray && utilityScenePick) {
  95463. prePointerInfo.ray = utilityScenePick.ray;
  95464. }
  95465. // always fire the prepointer oversvable
  95466. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  95467. // allow every non pointer down event to flow to the utility layer
  95468. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  95469. if (!prePointerInfo.skipOnPointerObservable) {
  95470. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95471. }
  95472. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  95473. _this._pointerCaptures[pointerEvent.pointerId] = false;
  95474. }
  95475. return;
  95476. }
  95477. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  95478. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  95479. if (utilityScenePick && utilityScenePick.hit) {
  95480. if (!prePointerInfo.skipOnPointerObservable) {
  95481. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  95482. }
  95483. prePointerInfo.skipOnPointerObservable = true;
  95484. }
  95485. }
  95486. else {
  95487. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  95488. var pointerEvent_1 = (prePointerInfo.event);
  95489. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  95490. if (originalScenePick && utilityScenePick) {
  95491. // No pick in utility scene
  95492. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  95493. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95494. // We touched an utility mesh present in the main scene
  95495. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95496. prePointerInfo.skipOnPointerObservable = true;
  95497. }
  95498. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95499. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  95500. }
  95501. }
  95502. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  95503. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  95504. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  95505. // If a previous utility layer set this, do not unset this
  95506. if (!prePointerInfo.skipOnPointerObservable) {
  95507. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  95508. }
  95509. }
  95510. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  95511. // We have a pick in both scenes but main is closer than utility
  95512. // We touched an utility mesh present in the main scene
  95513. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  95514. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  95515. prePointerInfo.skipOnPointerObservable = true;
  95516. }
  95517. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  95518. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  95519. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  95520. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  95521. }
  95522. }
  95523. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  95524. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  95525. }
  95526. }
  95527. }
  95528. });
  95529. // Render directly on top of existing scene without clearing
  95530. this.utilityLayerScene.autoClear = false;
  95531. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  95532. if (_this.shouldRender) {
  95533. _this.render();
  95534. }
  95535. });
  95536. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  95537. _this.dispose();
  95538. });
  95539. this._updateCamera();
  95540. }
  95541. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  95542. /**
  95543. * 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)
  95544. */
  95545. get: function () {
  95546. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  95547. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95548. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95549. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95550. });
  95551. }
  95552. return UtilityLayerRenderer._DefaultUtilityLayer;
  95553. },
  95554. enumerable: true,
  95555. configurable: true
  95556. });
  95557. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  95558. /**
  95559. * 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)
  95560. */
  95561. get: function () {
  95562. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  95563. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  95564. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  95565. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  95566. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95567. });
  95568. }
  95569. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  95570. },
  95571. enumerable: true,
  95572. configurable: true
  95573. });
  95574. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  95575. if (!prePointerInfo.skipOnPointerObservable) {
  95576. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  95577. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  95578. }
  95579. };
  95580. /**
  95581. * Renders the utility layers scene on top of the original scene
  95582. */
  95583. UtilityLayerRenderer.prototype.render = function () {
  95584. this._updateCamera();
  95585. if (this.utilityLayerScene.activeCamera) {
  95586. // Set the camera's scene to utility layers scene
  95587. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  95588. var camera = this.utilityLayerScene.activeCamera;
  95589. camera._scene = this.utilityLayerScene;
  95590. if (camera.leftCamera) {
  95591. camera.leftCamera._scene = this.utilityLayerScene;
  95592. }
  95593. if (camera.rightCamera) {
  95594. camera.rightCamera._scene = this.utilityLayerScene;
  95595. }
  95596. this.utilityLayerScene.render(false);
  95597. // Reset camera's scene back to original
  95598. camera._scene = oldScene;
  95599. if (camera.leftCamera) {
  95600. camera.leftCamera._scene = oldScene;
  95601. }
  95602. if (camera.rightCamera) {
  95603. camera.rightCamera._scene = oldScene;
  95604. }
  95605. }
  95606. };
  95607. /**
  95608. * Disposes of the renderer
  95609. */
  95610. UtilityLayerRenderer.prototype.dispose = function () {
  95611. this.onPointerOutObservable.clear();
  95612. if (this._afterRenderObserver) {
  95613. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  95614. }
  95615. if (this._sceneDisposeObserver) {
  95616. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95617. }
  95618. if (this._originalPointerObserver) {
  95619. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  95620. }
  95621. this.utilityLayerScene.dispose();
  95622. };
  95623. UtilityLayerRenderer.prototype._updateCamera = function () {
  95624. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  95625. };
  95626. UtilityLayerRenderer._DefaultUtilityLayer = null;
  95627. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  95628. return UtilityLayerRenderer;
  95629. }());
  95630. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  95631. })(BABYLON || (BABYLON = {}));
  95632. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  95633. //# sourceMappingURL=babylon.behavior.js.map
  95634. var BABYLON;
  95635. (function (BABYLON) {
  95636. /**
  95637. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95638. */
  95639. var PointerDragBehavior = /** @class */ (function () {
  95640. /**
  95641. * Creates a pointer drag behavior that can be attached to a mesh
  95642. * @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)
  95643. */
  95644. function PointerDragBehavior(options) {
  95645. /**
  95646. * 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)
  95647. */
  95648. this.maxDragAngle = 0;
  95649. /**
  95650. * @hidden
  95651. */
  95652. this._useAlternatePickedPointAboveMaxDragAngle = false;
  95653. /**
  95654. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95655. */
  95656. this.currentDraggingPointerID = -1;
  95657. /**
  95658. * If the behavior is currently in a dragging state
  95659. */
  95660. this.dragging = false;
  95661. /**
  95662. * 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)
  95663. */
  95664. this.dragDeltaRatio = 0.2;
  95665. /**
  95666. * If the drag plane orientation should be updated during the dragging (Default: true)
  95667. */
  95668. this.updateDragPlane = true;
  95669. // Debug mode will display drag planes to help visualize behavior
  95670. this._debugMode = false;
  95671. this._moving = false;
  95672. /**
  95673. * Fires each time the attached mesh is dragged with the pointer
  95674. * * delta between last drag position and current drag position in world space
  95675. * * dragDistance along the drag axis
  95676. * * dragPlaneNormal normal of the current drag plane used during the drag
  95677. * * dragPlanePoint in world space where the drag intersects the drag plane
  95678. */
  95679. this.onDragObservable = new BABYLON.Observable();
  95680. /**
  95681. * Fires each time a drag begins (eg. mouse down on mesh)
  95682. */
  95683. this.onDragStartObservable = new BABYLON.Observable();
  95684. /**
  95685. * Fires each time a drag ends (eg. mouse release after drag)
  95686. */
  95687. this.onDragEndObservable = new BABYLON.Observable();
  95688. /**
  95689. * If the attached mesh should be moved when dragged
  95690. */
  95691. this.moveAttached = true;
  95692. /**
  95693. * If the drag behavior will react to drag events (Default: true)
  95694. */
  95695. this.enabled = true;
  95696. /**
  95697. * If camera controls should be detached during the drag
  95698. */
  95699. this.detachCameraControls = true;
  95700. /**
  95701. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  95702. */
  95703. this.useObjectOrienationForDragging = true;
  95704. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  95705. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  95706. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  95707. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95708. this._attachedElement = null;
  95709. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95710. this._lastPointerRay = {};
  95711. this._dragDelta = new BABYLON.Vector3();
  95712. // Variables to avoid instantiation in the below method
  95713. this._pointA = new BABYLON.Vector3(0, 0, 0);
  95714. this._pointB = new BABYLON.Vector3(0, 0, 0);
  95715. this._pointC = new BABYLON.Vector3(0, 0, 0);
  95716. this._lineA = new BABYLON.Vector3(0, 0, 0);
  95717. this._lineB = new BABYLON.Vector3(0, 0, 0);
  95718. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  95719. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  95720. this._options = options ? options : {};
  95721. var optionCount = 0;
  95722. if (this._options.dragAxis) {
  95723. optionCount++;
  95724. }
  95725. if (this._options.dragPlaneNormal) {
  95726. optionCount++;
  95727. }
  95728. if (optionCount > 1) {
  95729. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95730. }
  95731. }
  95732. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95733. /**
  95734. * The name of the behavior
  95735. */
  95736. get: function () {
  95737. return "PointerDrag";
  95738. },
  95739. enumerable: true,
  95740. configurable: true
  95741. });
  95742. /**
  95743. * Initializes the behavior
  95744. */
  95745. PointerDragBehavior.prototype.init = function () { };
  95746. /**
  95747. * Attaches the drag behavior the passed in mesh
  95748. * @param ownerNode The mesh that will be dragged around once attached
  95749. */
  95750. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95751. var _this = this;
  95752. this._scene = ownerNode.getScene();
  95753. this._attachedNode = ownerNode;
  95754. // Initialize drag plane to not interfere with existing scene
  95755. if (!PointerDragBehavior._planeScene) {
  95756. if (this._debugMode) {
  95757. PointerDragBehavior._planeScene = this._scene;
  95758. }
  95759. else {
  95760. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95761. PointerDragBehavior._planeScene.detachControl();
  95762. this._scene.getEngine().scenes.pop();
  95763. this._scene.onDisposeObservable.addOnce(function () {
  95764. PointerDragBehavior._planeScene.dispose();
  95765. PointerDragBehavior._planeScene = null;
  95766. });
  95767. }
  95768. }
  95769. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95770. // State of the drag
  95771. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  95772. var pickPredicate = function (m) {
  95773. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95774. };
  95775. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95776. if (!_this.enabled) {
  95777. return;
  95778. }
  95779. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95780. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95781. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  95782. }
  95783. }
  95784. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95785. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95786. _this.releaseDrag();
  95787. }
  95788. }
  95789. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95790. var pointerId = pointerInfo.event.pointerId;
  95791. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  95792. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  95793. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  95794. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  95795. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  95796. }
  95797. _this.currentDraggingPointerID = pointerId;
  95798. }
  95799. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  95800. if (!_this._lastPointerRay[pointerId]) {
  95801. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  95802. }
  95803. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  95804. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  95805. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  95806. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  95807. _this._moveDrag(pointerInfo.pickInfo.ray);
  95808. }
  95809. }
  95810. }
  95811. });
  95812. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95813. if (_this._moving && _this.moveAttached) {
  95814. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  95815. // Slowly move mesh to avoid jitter
  95816. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  95817. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  95818. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  95819. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  95820. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  95821. }
  95822. });
  95823. };
  95824. /**
  95825. * Force relase the drag action by code.
  95826. */
  95827. PointerDragBehavior.prototype.releaseDrag = function () {
  95828. this.dragging = false;
  95829. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  95830. this.currentDraggingPointerID = -1;
  95831. this._moving = false;
  95832. // Reattach camera controls
  95833. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95834. this._scene.activeCamera.attachControl(this._attachedElement, true);
  95835. }
  95836. };
  95837. /**
  95838. * Simulates the start of a pointer drag event on the behavior
  95839. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  95840. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  95841. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  95842. */
  95843. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  95844. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  95845. this._startDrag(pointerId, fromRay, startPickedPoint);
  95846. var lastRay = this._lastPointerRay[pointerId];
  95847. if (pointerId === PointerDragBehavior._AnyMouseID) {
  95848. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  95849. }
  95850. if (lastRay) {
  95851. // if there was a last pointer ray drag the object there
  95852. this._moveDrag(lastRay);
  95853. }
  95854. };
  95855. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  95856. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  95857. return;
  95858. }
  95859. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  95860. // Create start ray from the camera to the object
  95861. if (fromRay) {
  95862. this._startDragRay.direction.copyFrom(fromRay.direction);
  95863. this._startDragRay.origin.copyFrom(fromRay.origin);
  95864. }
  95865. else {
  95866. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  95867. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  95868. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  95869. }
  95870. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  95871. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  95872. if (pickedPoint) {
  95873. this.dragging = true;
  95874. this.currentDraggingPointerID = pointerId;
  95875. this.lastDragPosition.copyFrom(pickedPoint);
  95876. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  95877. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  95878. // Detatch camera controls
  95879. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  95880. if (this._scene.activeCamera.inputs.attachedElement) {
  95881. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  95882. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  95883. }
  95884. else {
  95885. this._attachedElement = null;
  95886. }
  95887. }
  95888. }
  95889. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  95890. };
  95891. PointerDragBehavior.prototype._moveDrag = function (ray) {
  95892. this._moving = true;
  95893. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  95894. if (pickedPoint) {
  95895. if (this.updateDragPlane) {
  95896. this._updateDragPlanePosition(ray, pickedPoint);
  95897. }
  95898. var dragLength = 0;
  95899. // depending on the drag mode option drag accordingly
  95900. if (this._options.dragAxis) {
  95901. // Convert local drag axis to world
  95902. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  95903. // Project delta drag from the drag plane onto the drag axis
  95904. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  95905. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  95906. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  95907. }
  95908. else {
  95909. dragLength = this._dragDelta.length();
  95910. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  95911. }
  95912. this._targetPosition.addInPlace(this._dragDelta);
  95913. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  95914. this.lastDragPosition.copyFrom(pickedPoint);
  95915. }
  95916. };
  95917. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95918. var _this = this;
  95919. if (!ray) {
  95920. return null;
  95921. }
  95922. // Calculate angle between plane normal and ray
  95923. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  95924. // Correct if ray is casted from oposite side
  95925. if (angle > Math.PI / 2) {
  95926. angle = Math.PI - angle;
  95927. }
  95928. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  95929. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  95930. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  95931. // Invert ray direction along the towards object axis
  95932. this._tmpVector.copyFrom(ray.direction);
  95933. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  95934. this._alternatePickedPoint.normalize();
  95935. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  95936. this._tmpVector.addInPlace(this._alternatePickedPoint);
  95937. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  95938. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  95939. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  95940. this._alternatePickedPoint.addInPlace(this._tmpVector);
  95941. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  95942. return this._alternatePickedPoint;
  95943. }
  95944. else {
  95945. return null;
  95946. }
  95947. }
  95948. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95949. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95950. return pickResult.pickedPoint;
  95951. }
  95952. else {
  95953. return null;
  95954. }
  95955. };
  95956. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95957. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  95958. this._pointA.copyFrom(dragPlanePosition);
  95959. if (this._options.dragAxis) {
  95960. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  95961. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95962. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  95963. ray.origin.subtractToRef(this._pointA, this._pointC);
  95964. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  95965. // Get perpendicular line from direction to camera and drag axis
  95966. this._pointB.subtractToRef(this._pointA, this._lineA);
  95967. this._pointC.subtractToRef(this._pointA, this._lineB);
  95968. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  95969. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95970. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  95971. this._lookAt.normalize();
  95972. this._dragPlane.position.copyFrom(this._pointA);
  95973. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  95974. this._dragPlane.lookAt(this._lookAt);
  95975. }
  95976. else if (this._options.dragPlaneNormal) {
  95977. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  95978. this._dragPlane.position.copyFrom(this._pointA);
  95979. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  95980. this._dragPlane.lookAt(this._lookAt);
  95981. }
  95982. else {
  95983. this._dragPlane.position.copyFrom(this._pointA);
  95984. this._dragPlane.lookAt(ray.origin);
  95985. }
  95986. this._dragPlane.computeWorldMatrix(true);
  95987. };
  95988. /**
  95989. * Detaches the behavior from the mesh
  95990. */
  95991. PointerDragBehavior.prototype.detach = function () {
  95992. if (this._pointerObserver) {
  95993. this._scene.onPointerObservable.remove(this._pointerObserver);
  95994. }
  95995. if (this._beforeRenderObserver) {
  95996. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95997. }
  95998. };
  95999. PointerDragBehavior._AnyMouseID = -2;
  96000. return PointerDragBehavior;
  96001. }());
  96002. BABYLON.PointerDragBehavior = PointerDragBehavior;
  96003. })(BABYLON || (BABYLON = {}));
  96004. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  96005. var BABYLON;
  96006. (function (BABYLON) {
  96007. /**
  96008. * A behavior that when attached to a mesh will allow the mesh to be scaled
  96009. */
  96010. var MultiPointerScaleBehavior = /** @class */ (function () {
  96011. /**
  96012. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  96013. */
  96014. function MultiPointerScaleBehavior() {
  96015. this._startDistance = 0;
  96016. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  96017. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  96018. this._sceneRenderObserver = null;
  96019. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  96020. this._dragBehaviorA.moveAttached = false;
  96021. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  96022. this._dragBehaviorB.moveAttached = false;
  96023. }
  96024. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  96025. /**
  96026. * The name of the behavior
  96027. */
  96028. get: function () {
  96029. return "MultiPointerScale";
  96030. },
  96031. enumerable: true,
  96032. configurable: true
  96033. });
  96034. /**
  96035. * Initializes the behavior
  96036. */
  96037. MultiPointerScaleBehavior.prototype.init = function () { };
  96038. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  96039. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  96040. };
  96041. /**
  96042. * Attaches the scale behavior the passed in mesh
  96043. * @param ownerNode The mesh that will be scaled around once attached
  96044. */
  96045. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  96046. var _this = this;
  96047. this._ownerNode = ownerNode;
  96048. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  96049. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  96050. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96051. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96052. _this._dragBehaviorA.releaseDrag();
  96053. }
  96054. else {
  96055. _this._initialScale.copyFrom(ownerNode.scaling);
  96056. _this._startDistance = _this._getCurrentDistance();
  96057. }
  96058. }
  96059. });
  96060. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  96061. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96062. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  96063. _this._dragBehaviorB.releaseDrag();
  96064. }
  96065. else {
  96066. _this._initialScale.copyFrom(ownerNode.scaling);
  96067. _this._startDistance = _this._getCurrentDistance();
  96068. }
  96069. }
  96070. });
  96071. // Once both drag behaviors are active scale based on the distance between the two pointers
  96072. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96073. behavior.onDragObservable.add(function () {
  96074. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96075. var ratio = _this._getCurrentDistance() / _this._startDistance;
  96076. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  96077. }
  96078. });
  96079. });
  96080. ownerNode.addBehavior(this._dragBehaviorA);
  96081. ownerNode.addBehavior(this._dragBehaviorB);
  96082. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96083. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96084. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  96085. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  96086. if (change.length() > 0.01) {
  96087. ownerNode.scaling.addInPlace(change);
  96088. }
  96089. }
  96090. });
  96091. };
  96092. /**
  96093. * Detaches the behavior from the mesh
  96094. */
  96095. MultiPointerScaleBehavior.prototype.detach = function () {
  96096. var _this = this;
  96097. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96098. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  96099. behavior.onDragStartObservable.clear();
  96100. behavior.onDragObservable.clear();
  96101. _this._ownerNode.removeBehavior(behavior);
  96102. });
  96103. };
  96104. return MultiPointerScaleBehavior;
  96105. }());
  96106. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  96107. })(BABYLON || (BABYLON = {}));
  96108. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  96109. var BABYLON;
  96110. (function (BABYLON) {
  96111. /**
  96112. * 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
  96113. */
  96114. var SixDofDragBehavior = /** @class */ (function () {
  96115. /**
  96116. * 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
  96117. */
  96118. function SixDofDragBehavior() {
  96119. this._sceneRenderObserver = null;
  96120. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  96121. this._moving = false;
  96122. this._startingOrientation = new BABYLON.Quaternion();
  96123. /**
  96124. * 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)
  96125. */
  96126. this.zDragFactor = 3;
  96127. /**
  96128. * If the behavior is currently in a dragging state
  96129. */
  96130. this.dragging = false;
  96131. /**
  96132. * 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)
  96133. */
  96134. this.dragDeltaRatio = 0.2;
  96135. /**
  96136. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  96137. */
  96138. this.currentDraggingPointerID = -1;
  96139. /**
  96140. * If camera controls should be detached during the drag
  96141. */
  96142. this.detachCameraControls = true;
  96143. /**
  96144. * Fires each time a drag starts
  96145. */
  96146. this.onDragStartObservable = new BABYLON.Observable();
  96147. /**
  96148. * Fires each time a drag ends (eg. mouse release after drag)
  96149. */
  96150. this.onDragEndObservable = new BABYLON.Observable();
  96151. }
  96152. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  96153. /**
  96154. * The name of the behavior
  96155. */
  96156. get: function () {
  96157. return "SixDofDrag";
  96158. },
  96159. enumerable: true,
  96160. configurable: true
  96161. });
  96162. /**
  96163. * Initializes the behavior
  96164. */
  96165. SixDofDragBehavior.prototype.init = function () { };
  96166. /**
  96167. * Attaches the scale behavior the passed in mesh
  96168. * @param ownerNode The mesh that will be scaled around once attached
  96169. */
  96170. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  96171. var _this = this;
  96172. this._ownerNode = ownerNode;
  96173. this._scene = this._ownerNode.getScene();
  96174. if (!SixDofDragBehavior._virtualScene) {
  96175. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  96176. this._scene.getEngine().scenes.pop();
  96177. }
  96178. var pickedMesh = null;
  96179. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  96180. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  96181. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96182. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  96183. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  96184. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  96185. var pickPredicate = function (m) {
  96186. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  96187. };
  96188. var attachedElement = null;
  96189. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  96190. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96191. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  96192. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96193. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96194. }
  96195. pickedMesh = _this._ownerNode;
  96196. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96197. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96198. // Set position and orientation of the controller
  96199. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96200. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96201. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  96202. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96203. pickedMesh.computeWorldMatrix();
  96204. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  96205. if (!pickedMesh.rotationQuaternion) {
  96206. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  96207. }
  96208. var oldParent = pickedMesh.parent;
  96209. pickedMesh.setParent(null);
  96210. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  96211. pickedMesh.setParent(oldParent);
  96212. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96213. // Update state
  96214. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96215. _this.dragging = true;
  96216. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  96217. // Detatch camera controls
  96218. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96219. if (_this._scene.activeCamera.inputs.attachedElement) {
  96220. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  96221. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  96222. }
  96223. else {
  96224. attachedElement = null;
  96225. }
  96226. }
  96227. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96228. _this.onDragStartObservable.notifyObservers({});
  96229. }
  96230. }
  96231. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  96232. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  96233. _this.dragging = false;
  96234. _this._moving = false;
  96235. _this.currentDraggingPointerID = -1;
  96236. pickedMesh = null;
  96237. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96238. // Reattach camera controls
  96239. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  96240. _this._scene.activeCamera.attachControl(attachedElement, true);
  96241. }
  96242. _this.onDragEndObservable.notifyObservers({});
  96243. }
  96244. }
  96245. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  96246. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  96247. var zDragFactor = _this.zDragFactor;
  96248. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  96249. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  96250. zDragFactor = 0;
  96251. }
  96252. // Calculate controller drag distance in controller space
  96253. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  96254. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  96255. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  96256. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  96257. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  96258. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  96259. if (_this._virtualDragMesh.position.z < 0) {
  96260. _this._virtualDragMesh.position.z = 0;
  96261. }
  96262. // Update the controller position
  96263. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  96264. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  96265. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  96266. // Move the virtualObjectsPosition into the picked mesh's space if needed
  96267. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  96268. if (pickedMesh.parent) {
  96269. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  96270. }
  96271. if (!_this._moving) {
  96272. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  96273. }
  96274. _this._moving = true;
  96275. }
  96276. }
  96277. });
  96278. var tmpQuaternion = new BABYLON.Quaternion();
  96279. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  96280. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  96281. if (_this.dragging && _this._moving && pickedMesh) {
  96282. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  96283. // Slowly move mesh to avoid jitter
  96284. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  96285. // Get change in rotation
  96286. tmpQuaternion.copyFrom(_this._startingOrientation);
  96287. tmpQuaternion.x = -tmpQuaternion.x;
  96288. tmpQuaternion.y = -tmpQuaternion.y;
  96289. tmpQuaternion.z = -tmpQuaternion.z;
  96290. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  96291. // Convert change in rotation to only y axis rotation
  96292. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  96293. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  96294. // Slowly move mesh to avoid jitter
  96295. var oldParent = pickedMesh.parent;
  96296. pickedMesh.setParent(null);
  96297. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  96298. pickedMesh.setParent(oldParent);
  96299. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  96300. }
  96301. });
  96302. };
  96303. /**
  96304. * Detaches the behavior from the mesh
  96305. */
  96306. SixDofDragBehavior.prototype.detach = function () {
  96307. if (this._scene) {
  96308. this._scene.onPointerObservable.remove(this._pointerObserver);
  96309. }
  96310. if (this._ownerNode) {
  96311. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  96312. }
  96313. if (this._virtualOriginMesh) {
  96314. this._virtualOriginMesh.dispose();
  96315. }
  96316. if (this._virtualDragMesh) {
  96317. this._virtualDragMesh.dispose();
  96318. }
  96319. this.onDragEndObservable.clear();
  96320. this.onDragStartObservable.clear();
  96321. };
  96322. return SixDofDragBehavior;
  96323. }());
  96324. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  96325. })(BABYLON || (BABYLON = {}));
  96326. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  96327. var BABYLON;
  96328. (function (BABYLON) {
  96329. /**
  96330. * @hidden
  96331. */
  96332. var FaceDirectionInfo = /** @class */ (function () {
  96333. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  96334. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  96335. if (diff === void 0) { diff = 0; }
  96336. if (ignore === void 0) { ignore = false; }
  96337. this.direction = direction;
  96338. this.rotatedDirection = rotatedDirection;
  96339. this.diff = diff;
  96340. this.ignore = ignore;
  96341. }
  96342. return FaceDirectionInfo;
  96343. }());
  96344. /**
  96345. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  96346. */
  96347. var AttachToBoxBehavior = /** @class */ (function () {
  96348. /**
  96349. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  96350. * @param ui The transform node that should be attched to the mesh
  96351. */
  96352. function AttachToBoxBehavior(ui) {
  96353. this.ui = ui;
  96354. /**
  96355. * The name of the behavior
  96356. */
  96357. this.name = "AttachToBoxBehavior";
  96358. /**
  96359. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  96360. */
  96361. this.distanceAwayFromFace = 0.15;
  96362. /**
  96363. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  96364. */
  96365. this.distanceAwayFromBottomOfFace = 0.15;
  96366. 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))];
  96367. this._tmpMatrix = new BABYLON.Matrix();
  96368. this._tmpVector = new BABYLON.Vector3();
  96369. this._zeroVector = BABYLON.Vector3.Zero();
  96370. this._lookAtTmpMatrix = new BABYLON.Matrix();
  96371. /* Does nothing */
  96372. }
  96373. /**
  96374. * Initializes the behavior
  96375. */
  96376. AttachToBoxBehavior.prototype.init = function () {
  96377. /* Does nothing */
  96378. };
  96379. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  96380. var _this = this;
  96381. // Go over each face and calculate the angle between the face's normal and targetDirection
  96382. this._faceVectors.forEach(function (v) {
  96383. if (!_this._target.rotationQuaternion) {
  96384. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  96385. }
  96386. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  96387. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  96388. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  96389. });
  96390. // Return the face information of the one with the normal closeset to target direction
  96391. return this._faceVectors.reduce(function (min, p) {
  96392. if (min.ignore) {
  96393. return p;
  96394. }
  96395. else if (p.ignore) {
  96396. return min;
  96397. }
  96398. else {
  96399. return min.diff < p.diff ? min : p;
  96400. }
  96401. }, this._faceVectors[0]);
  96402. };
  96403. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  96404. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  96405. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  96406. this._lookAtTmpMatrix.invert();
  96407. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  96408. };
  96409. /**
  96410. * Attaches the AttachToBoxBehavior to the passed in mesh
  96411. * @param target The mesh that the specified node will be attached to
  96412. */
  96413. AttachToBoxBehavior.prototype.attach = function (target) {
  96414. var _this = this;
  96415. this._target = target;
  96416. this._scene = this._target.getScene();
  96417. // Every frame, update the app bars position
  96418. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  96419. if (!_this._scene.activeCamera) {
  96420. return;
  96421. }
  96422. // Find the face closest to the cameras position
  96423. var cameraPos = _this._scene.activeCamera.position;
  96424. if (_this._scene.activeCamera.devicePosition) {
  96425. cameraPos = _this._scene.activeCamera.devicePosition;
  96426. }
  96427. var facing = _this._closestFace(cameraPos.subtract(target.position));
  96428. if (_this._scene.activeCamera.leftCamera) {
  96429. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96430. }
  96431. else {
  96432. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  96433. }
  96434. // Get camera up direction
  96435. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  96436. // Ignore faces to not select a parrelel face for the up vector of the UI
  96437. _this._faceVectors.forEach(function (v) {
  96438. if (facing.direction.x && v.direction.x) {
  96439. v.ignore = true;
  96440. }
  96441. if (facing.direction.y && v.direction.y) {
  96442. v.ignore = true;
  96443. }
  96444. if (facing.direction.z && v.direction.z) {
  96445. v.ignore = true;
  96446. }
  96447. });
  96448. var facingUp = _this._closestFace(_this._tmpVector);
  96449. // Unignore faces
  96450. _this._faceVectors.forEach(function (v) {
  96451. v.ignore = false;
  96452. });
  96453. // Position the app bar on that face
  96454. _this.ui.position.copyFrom(target.position);
  96455. if (facing.direction.x) {
  96456. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96457. _this.ui.position.addInPlace(_this._tmpVector);
  96458. }
  96459. if (facing.direction.y) {
  96460. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96461. _this.ui.position.addInPlace(_this._tmpVector);
  96462. }
  96463. if (facing.direction.z) {
  96464. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  96465. _this.ui.position.addInPlace(_this._tmpVector);
  96466. }
  96467. // Rotate to be oriented properly to the camera
  96468. if (!_this.ui.rotationQuaternion) {
  96469. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  96470. }
  96471. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  96472. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  96473. // Place ui the correct distance from the bottom of the mesh
  96474. if (facingUp.direction.x) {
  96475. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  96476. }
  96477. if (facingUp.direction.y) {
  96478. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  96479. }
  96480. if (facingUp.direction.z) {
  96481. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  96482. }
  96483. _this.ui.position.addInPlace(_this._tmpVector);
  96484. });
  96485. };
  96486. /**
  96487. * Detaches the behavior from the mesh
  96488. */
  96489. AttachToBoxBehavior.prototype.detach = function () {
  96490. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  96491. };
  96492. return AttachToBoxBehavior;
  96493. }());
  96494. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  96495. })(BABYLON || (BABYLON = {}));
  96496. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  96497. var BABYLON;
  96498. (function (BABYLON) {
  96499. /**
  96500. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  96501. */
  96502. var FadeInOutBehavior = /** @class */ (function () {
  96503. /**
  96504. * Instatiates the FadeInOutBehavior
  96505. */
  96506. function FadeInOutBehavior() {
  96507. var _this = this;
  96508. /**
  96509. * Time in milliseconds to delay before fading in (Default: 0)
  96510. */
  96511. this.delay = 0;
  96512. /**
  96513. * Time in milliseconds for the mesh to fade in (Default: 300)
  96514. */
  96515. this.fadeInTime = 300;
  96516. this._millisecondsPerFrame = 1000 / 60;
  96517. this._hovered = false;
  96518. this._hoverValue = 0;
  96519. this._ownerNode = null;
  96520. this._update = function () {
  96521. if (_this._ownerNode) {
  96522. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  96523. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  96524. if (_this._ownerNode.visibility > 1) {
  96525. _this._setAllVisibility(_this._ownerNode, 1);
  96526. _this._hoverValue = _this.fadeInTime + _this.delay;
  96527. return;
  96528. }
  96529. else if (_this._ownerNode.visibility < 0) {
  96530. _this._setAllVisibility(_this._ownerNode, 0);
  96531. if (_this._hoverValue < 0) {
  96532. _this._hoverValue = 0;
  96533. return;
  96534. }
  96535. }
  96536. setTimeout(_this._update, _this._millisecondsPerFrame);
  96537. }
  96538. };
  96539. }
  96540. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  96541. /**
  96542. * The name of the behavior
  96543. */
  96544. get: function () {
  96545. return "FadeInOut";
  96546. },
  96547. enumerable: true,
  96548. configurable: true
  96549. });
  96550. /**
  96551. * Initializes the behavior
  96552. */
  96553. FadeInOutBehavior.prototype.init = function () {
  96554. };
  96555. /**
  96556. * Attaches the fade behavior on the passed in mesh
  96557. * @param ownerNode The mesh that will be faded in/out once attached
  96558. */
  96559. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  96560. this._ownerNode = ownerNode;
  96561. this._setAllVisibility(this._ownerNode, 0);
  96562. };
  96563. /**
  96564. * Detaches the behavior from the mesh
  96565. */
  96566. FadeInOutBehavior.prototype.detach = function () {
  96567. this._ownerNode = null;
  96568. };
  96569. /**
  96570. * Triggers the mesh to begin fading in or out
  96571. * @param value if the object should fade in or out (true to fade in)
  96572. */
  96573. FadeInOutBehavior.prototype.fadeIn = function (value) {
  96574. this._hovered = value;
  96575. this._update();
  96576. };
  96577. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  96578. var _this = this;
  96579. mesh.visibility = value;
  96580. mesh.getChildMeshes().forEach(function (c) {
  96581. _this._setAllVisibility(c, value);
  96582. });
  96583. };
  96584. return FadeInOutBehavior;
  96585. }());
  96586. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  96587. })(BABYLON || (BABYLON = {}));
  96588. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  96589. var BABYLON;
  96590. (function (BABYLON) {
  96591. /**
  96592. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  96593. */
  96594. var Gizmo = /** @class */ (function () {
  96595. /**
  96596. * Creates a gizmo
  96597. * @param gizmoLayer The utility layer the gizmo will be added to
  96598. */
  96599. function Gizmo(
  96600. /** The utility layer the gizmo will be added to */
  96601. gizmoLayer) {
  96602. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96603. var _this = this;
  96604. this.gizmoLayer = gizmoLayer;
  96605. /**
  96606. * Ratio for the scale of the gizmo (Default: 1)
  96607. */
  96608. this.scaleRatio = 1;
  96609. this._tmpMatrix = new BABYLON.Matrix();
  96610. /**
  96611. * If a custom mesh has been set (Default: false)
  96612. */
  96613. this._customMeshSet = false;
  96614. /**
  96615. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  96616. */
  96617. this.updateGizmoRotationToMatchAttachedMesh = true;
  96618. /**
  96619. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  96620. */
  96621. this.updateGizmoPositionToMatchAttachedMesh = true;
  96622. /**
  96623. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  96624. */
  96625. this._updateScale = true;
  96626. this._interactionsEnabled = true;
  96627. this._tempVector = new BABYLON.Vector3();
  96628. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  96629. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  96630. _this._update();
  96631. });
  96632. this.attachedMesh = null;
  96633. }
  96634. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  96635. /**
  96636. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  96637. * * When set, interactions will be enabled
  96638. */
  96639. get: function () {
  96640. return this._attachedMesh;
  96641. },
  96642. set: function (value) {
  96643. this._attachedMesh = value;
  96644. this._rootMesh.setEnabled(value ? true : false);
  96645. this._attachedMeshChanged(value);
  96646. },
  96647. enumerable: true,
  96648. configurable: true
  96649. });
  96650. /**
  96651. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96652. * @param mesh The mesh to replace the default mesh of the gizmo
  96653. */
  96654. Gizmo.prototype.setCustomMesh = function (mesh) {
  96655. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  96656. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  96657. }
  96658. this._rootMesh.getChildMeshes().forEach(function (c) {
  96659. c.dispose();
  96660. });
  96661. mesh.parent = this._rootMesh;
  96662. this._customMeshSet = true;
  96663. };
  96664. Gizmo.prototype._attachedMeshChanged = function (value) {
  96665. };
  96666. /**
  96667. * @hidden
  96668. * Updates the gizmo to match the attached mesh's position/rotation
  96669. */
  96670. Gizmo.prototype._update = function () {
  96671. if (this.attachedMesh) {
  96672. if (this.updateGizmoRotationToMatchAttachedMesh) {
  96673. if (!this._rootMesh.rotationQuaternion) {
  96674. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  96675. }
  96676. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  96677. this._tempVector.copyFrom(this.attachedMesh.scaling);
  96678. if (this.attachedMesh.scaling.x < 0) {
  96679. this.attachedMesh.scaling.x *= -1;
  96680. }
  96681. if (this.attachedMesh.scaling.y < 0) {
  96682. this.attachedMesh.scaling.y *= -1;
  96683. }
  96684. if (this.attachedMesh.scaling.z < 0) {
  96685. this.attachedMesh.scaling.z *= -1;
  96686. }
  96687. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  96688. this.attachedMesh.scaling.copyFrom(this._tempVector);
  96689. this.attachedMesh.computeWorldMatrix();
  96690. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  96691. }
  96692. else if (this._rootMesh.rotationQuaternion) {
  96693. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  96694. }
  96695. if (this.updateGizmoPositionToMatchAttachedMesh) {
  96696. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  96697. }
  96698. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  96699. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  96700. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  96701. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  96702. }
  96703. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  96704. var dist = this._tempVector.length() * this.scaleRatio;
  96705. this._rootMesh.scaling.set(dist, dist, dist);
  96706. }
  96707. }
  96708. };
  96709. /**
  96710. * Disposes of the gizmo
  96711. */
  96712. Gizmo.prototype.dispose = function () {
  96713. this._rootMesh.dispose();
  96714. if (this._beforeRenderObserver) {
  96715. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  96716. }
  96717. };
  96718. return Gizmo;
  96719. }());
  96720. BABYLON.Gizmo = Gizmo;
  96721. })(BABYLON || (BABYLON = {}));
  96722. //# sourceMappingURL=babylon.gizmo.js.map
  96723. var BABYLON;
  96724. (function (BABYLON) {
  96725. /**
  96726. * Single axis drag gizmo
  96727. */
  96728. var AxisDragGizmo = /** @class */ (function (_super) {
  96729. __extends(AxisDragGizmo, _super);
  96730. /**
  96731. * Creates an AxisDragGizmo
  96732. * @param gizmoLayer The utility layer the gizmo will be added to
  96733. * @param dragAxis The axis which the gizmo will be able to drag on
  96734. * @param color The color of the gizmo
  96735. */
  96736. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  96737. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96738. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96739. var _this = _super.call(this, gizmoLayer) || this;
  96740. _this._pointerObserver = null;
  96741. /**
  96742. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96743. */
  96744. _this.snapDistance = 0;
  96745. /**
  96746. * Event that fires each time the gizmo snaps to a new location.
  96747. * * snapDistance is the the change in distance
  96748. */
  96749. _this.onSnapObservable = new BABYLON.Observable();
  96750. // Create Material
  96751. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96752. coloredMaterial.disableLighting = true;
  96753. coloredMaterial.emissiveColor = color;
  96754. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96755. hoverMaterial.disableLighting = true;
  96756. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96757. // Build mesh on root node
  96758. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96759. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  96760. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96761. arrowTail.color = coloredMaterial.emissiveColor;
  96762. arrow.addChild(arrowMesh);
  96763. arrow.addChild(arrowTail);
  96764. // Position arrow pointing in its drag axis
  96765. arrowMesh.scaling.scaleInPlace(0.05);
  96766. arrowMesh.material = coloredMaterial;
  96767. arrowMesh.rotation.x = Math.PI / 2;
  96768. arrowMesh.position.z += 0.3;
  96769. arrowTail.scaling.scaleInPlace(0.26);
  96770. arrowTail.rotation.x = Math.PI / 2;
  96771. arrowTail.material = coloredMaterial;
  96772. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96773. arrow.scaling.scaleInPlace(1 / 3);
  96774. _this._rootMesh.addChild(arrow);
  96775. var currentSnapDragDistance = 0;
  96776. var tmpVector = new BABYLON.Vector3();
  96777. var tmpSnapEvent = { snapDistance: 0 };
  96778. // Add drag behavior to handle events when the gizmo is dragged
  96779. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96780. _this.dragBehavior.moveAttached = false;
  96781. _this._rootMesh.addBehavior(_this.dragBehavior);
  96782. var localDelta = new BABYLON.Vector3();
  96783. var tmpMatrix = new BABYLON.Matrix();
  96784. _this.dragBehavior.onDragObservable.add(function (event) {
  96785. if (_this.attachedMesh) {
  96786. // Convert delta to local translation if it has a parent
  96787. if (_this.attachedMesh.parent) {
  96788. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96789. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  96790. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  96791. }
  96792. else {
  96793. localDelta.copyFrom(event.delta);
  96794. }
  96795. // Snapping logic
  96796. if (_this.snapDistance == 0) {
  96797. _this.attachedMesh.position.addInPlace(localDelta);
  96798. }
  96799. else {
  96800. currentSnapDragDistance += event.dragDistance;
  96801. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96802. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  96803. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96804. localDelta.normalizeToRef(tmpVector);
  96805. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  96806. _this.attachedMesh.position.addInPlace(tmpVector);
  96807. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96808. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96809. }
  96810. }
  96811. }
  96812. });
  96813. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96814. if (_this._customMeshSet) {
  96815. return;
  96816. }
  96817. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96818. var material = isHovered ? hoverMaterial : coloredMaterial;
  96819. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96820. m.material = material;
  96821. if (m.color) {
  96822. m.color = material.emissiveColor;
  96823. }
  96824. });
  96825. });
  96826. return _this;
  96827. }
  96828. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  96829. if (this.dragBehavior) {
  96830. this.dragBehavior.enabled = value ? true : false;
  96831. }
  96832. };
  96833. /**
  96834. * Disposes of the gizmo
  96835. */
  96836. AxisDragGizmo.prototype.dispose = function () {
  96837. this.onSnapObservable.clear();
  96838. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96839. this.dragBehavior.detach();
  96840. _super.prototype.dispose.call(this);
  96841. };
  96842. return AxisDragGizmo;
  96843. }(BABYLON.Gizmo));
  96844. BABYLON.AxisDragGizmo = AxisDragGizmo;
  96845. })(BABYLON || (BABYLON = {}));
  96846. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  96847. var BABYLON;
  96848. (function (BABYLON) {
  96849. /**
  96850. * Single axis scale gizmo
  96851. */
  96852. var AxisScaleGizmo = /** @class */ (function (_super) {
  96853. __extends(AxisScaleGizmo, _super);
  96854. /**
  96855. * Creates an AxisScaleGizmo
  96856. * @param gizmoLayer The utility layer the gizmo will be added to
  96857. * @param dragAxis The axis which the gizmo will be able to scale on
  96858. * @param color The color of the gizmo
  96859. */
  96860. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  96861. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96862. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96863. var _this = _super.call(this, gizmoLayer) || this;
  96864. _this._pointerObserver = null;
  96865. /**
  96866. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96867. */
  96868. _this.snapDistance = 0;
  96869. /**
  96870. * Event that fires each time the gizmo snaps to a new location.
  96871. * * snapDistance is the the change in distance
  96872. */
  96873. _this.onSnapObservable = new BABYLON.Observable();
  96874. /**
  96875. * If the scaling operation should be done on all axis (default: false)
  96876. */
  96877. _this.uniformScaling = false;
  96878. // Create Material
  96879. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96880. _this._coloredMaterial.disableLighting = true;
  96881. _this._coloredMaterial.emissiveColor = color;
  96882. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96883. hoverMaterial.disableLighting = true;
  96884. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96885. // Build mesh on root node
  96886. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96887. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  96888. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  96889. arrowTail.color = _this._coloredMaterial.emissiveColor;
  96890. arrow.addChild(arrowMesh);
  96891. arrow.addChild(arrowTail);
  96892. // Position arrow pointing in its drag axis
  96893. arrowMesh.scaling.scaleInPlace(0.1);
  96894. arrowMesh.material = _this._coloredMaterial;
  96895. arrowMesh.rotation.x = Math.PI / 2;
  96896. arrowMesh.position.z += 0.3;
  96897. arrowTail.scaling.scaleInPlace(0.26);
  96898. arrowTail.rotation.x = Math.PI / 2;
  96899. arrowTail.material = _this._coloredMaterial;
  96900. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  96901. _this._rootMesh.addChild(arrow);
  96902. arrow.scaling.scaleInPlace(1 / 3);
  96903. // Add drag behavior to handle events when the gizmo is dragged
  96904. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96905. _this.dragBehavior.moveAttached = false;
  96906. _this._rootMesh.addBehavior(_this.dragBehavior);
  96907. var currentSnapDragDistance = 0;
  96908. var tmpVector = new BABYLON.Vector3();
  96909. var tmpSnapEvent = { snapDistance: 0 };
  96910. _this.dragBehavior.onDragObservable.add(function (event) {
  96911. if (_this.attachedMesh) {
  96912. // Snapping logic
  96913. var snapped = false;
  96914. var dragSteps = 0;
  96915. if (_this.uniformScaling) {
  96916. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  96917. if (tmpVector.y < 0) {
  96918. tmpVector.scaleInPlace(-1);
  96919. }
  96920. }
  96921. else {
  96922. tmpVector.copyFrom(dragAxis);
  96923. }
  96924. if (_this.snapDistance == 0) {
  96925. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  96926. }
  96927. else {
  96928. currentSnapDragDistance += event.dragDistance;
  96929. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96930. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96931. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96932. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  96933. snapped = true;
  96934. }
  96935. else {
  96936. tmpVector.scaleInPlace(0);
  96937. }
  96938. }
  96939. _this.attachedMesh.scaling.addInPlace(tmpVector);
  96940. if (snapped) {
  96941. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  96942. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96943. }
  96944. }
  96945. });
  96946. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96947. if (_this._customMeshSet) {
  96948. return;
  96949. }
  96950. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96951. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  96952. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96953. m.material = material;
  96954. if (m.color) {
  96955. m.color = material.emissiveColor;
  96956. }
  96957. });
  96958. });
  96959. return _this;
  96960. }
  96961. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  96962. if (this.dragBehavior) {
  96963. this.dragBehavior.enabled = value ? true : false;
  96964. }
  96965. };
  96966. /**
  96967. * Disposes of the gizmo
  96968. */
  96969. AxisScaleGizmo.prototype.dispose = function () {
  96970. this.onSnapObservable.clear();
  96971. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96972. this.dragBehavior.detach();
  96973. _super.prototype.dispose.call(this);
  96974. };
  96975. /**
  96976. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  96977. * @param mesh The mesh to replace the default mesh of the gizmo
  96978. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  96979. */
  96980. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  96981. var _this = this;
  96982. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  96983. _super.prototype.setCustomMesh.call(this, mesh);
  96984. if (useGizmoMaterial) {
  96985. this._rootMesh.getChildMeshes().forEach(function (m) {
  96986. m.material = _this._coloredMaterial;
  96987. if (m.color) {
  96988. m.color = _this._coloredMaterial.emissiveColor;
  96989. }
  96990. });
  96991. this._customMeshSet = false;
  96992. }
  96993. };
  96994. return AxisScaleGizmo;
  96995. }(BABYLON.Gizmo));
  96996. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  96997. })(BABYLON || (BABYLON = {}));
  96998. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  96999. var BABYLON;
  97000. (function (BABYLON) {
  97001. /**
  97002. * Single plane rotation gizmo
  97003. */
  97004. var PlaneRotationGizmo = /** @class */ (function (_super) {
  97005. __extends(PlaneRotationGizmo, _super);
  97006. /**
  97007. * Creates a PlaneRotationGizmo
  97008. * @param gizmoLayer The utility layer the gizmo will be added to
  97009. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  97010. * @param color The color of the gizmo
  97011. */
  97012. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  97013. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97014. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97015. var _this = _super.call(this, gizmoLayer) || this;
  97016. _this._pointerObserver = null;
  97017. /**
  97018. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  97019. */
  97020. _this.snapDistance = 0;
  97021. /**
  97022. * Event that fires each time the gizmo snaps to a new location.
  97023. * * snapDistance is the the change in distance
  97024. */
  97025. _this.onSnapObservable = new BABYLON.Observable();
  97026. // Create Material
  97027. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97028. coloredMaterial.disableLighting = true;
  97029. coloredMaterial.emissiveColor = color;
  97030. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97031. hoverMaterial.disableLighting = true;
  97032. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97033. // Build mesh on root node
  97034. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97035. // Create circle out of lines
  97036. var tessellation = 20;
  97037. var radius = 0.8;
  97038. var points = new Array();
  97039. for (var i = 0; i < tessellation; i++) {
  97040. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  97041. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  97042. }
  97043. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  97044. rotationMesh.color = coloredMaterial.emissiveColor;
  97045. // Position arrow pointing in its drag axis
  97046. rotationMesh.scaling.scaleInPlace(0.26);
  97047. rotationMesh.material = coloredMaterial;
  97048. rotationMesh.rotation.x = Math.PI / 2;
  97049. parentMesh.addChild(rotationMesh);
  97050. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  97051. _this._rootMesh.addChild(parentMesh);
  97052. parentMesh.scaling.scaleInPlace(1 / 3);
  97053. // Add drag behavior to handle events when the gizmo is dragged
  97054. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  97055. _this.dragBehavior.moveAttached = false;
  97056. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  97057. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  97058. _this._rootMesh.addBehavior(_this.dragBehavior);
  97059. var lastDragPosition = new BABYLON.Vector3();
  97060. _this.dragBehavior.onDragStartObservable.add(function (e) {
  97061. if (_this.attachedMesh) {
  97062. lastDragPosition.copyFrom(e.dragPlanePoint);
  97063. }
  97064. });
  97065. var rotationMatrix = new BABYLON.Matrix();
  97066. var planeNormalTowardsCamera = new BABYLON.Vector3();
  97067. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  97068. var tmpSnapEvent = { snapDistance: 0 };
  97069. var currentSnapDragDistance = 0;
  97070. var tmpMatrix = new BABYLON.Matrix();
  97071. var tmpVector = new BABYLON.Vector3();
  97072. var amountToRotate = new BABYLON.Quaternion();
  97073. _this.dragBehavior.onDragObservable.add(function (event) {
  97074. if (_this.attachedMesh) {
  97075. if (!_this.attachedMesh.rotationQuaternion) {
  97076. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97077. }
  97078. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  97079. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  97080. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  97081. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  97082. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  97083. var angle = Math.atan2(cross.length(), dot);
  97084. planeNormalTowardsCamera.copyFrom(planeNormal);
  97085. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  97086. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97087. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  97088. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  97089. }
  97090. // Flip up vector depending on which side the camera is on
  97091. if (gizmoLayer.utilityLayerScene.activeCamera) {
  97092. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  97093. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  97094. planeNormalTowardsCamera.scaleInPlace(-1);
  97095. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  97096. }
  97097. }
  97098. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  97099. if (halfCircleSide)
  97100. angle = -angle;
  97101. // Snapping logic
  97102. var snapped = false;
  97103. if (_this.snapDistance != 0) {
  97104. currentSnapDragDistance += angle;
  97105. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  97106. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  97107. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  97108. angle = _this.snapDistance * dragSteps;
  97109. snapped = true;
  97110. }
  97111. else {
  97112. angle = 0;
  97113. }
  97114. }
  97115. // If the mesh has a parent, convert needed world rotation to local rotation
  97116. tmpMatrix.reset();
  97117. if (_this.attachedMesh.parent) {
  97118. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  97119. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  97120. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  97121. }
  97122. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  97123. var quaternionCoefficient = Math.sin(angle / 2);
  97124. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  97125. // 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
  97126. if (tmpMatrix.determinant() > 0) {
  97127. amountToRotate.toEulerAnglesToRef(tmpVector);
  97128. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  97129. }
  97130. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  97131. // Rotate selected mesh quaternion over fixed axis
  97132. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  97133. }
  97134. else {
  97135. // Rotate selected mesh quaternion over rotated axis
  97136. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  97137. }
  97138. lastDragPosition.copyFrom(event.dragPlanePoint);
  97139. if (snapped) {
  97140. tmpSnapEvent.snapDistance = angle;
  97141. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  97142. }
  97143. }
  97144. });
  97145. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97146. if (_this._customMeshSet) {
  97147. return;
  97148. }
  97149. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  97150. var material = isHovered ? hoverMaterial : coloredMaterial;
  97151. _this._rootMesh.getChildMeshes().forEach(function (m) {
  97152. m.material = material;
  97153. if (m.color) {
  97154. m.color = material.emissiveColor;
  97155. }
  97156. });
  97157. });
  97158. return _this;
  97159. }
  97160. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  97161. if (this.dragBehavior) {
  97162. this.dragBehavior.enabled = value ? true : false;
  97163. }
  97164. };
  97165. /**
  97166. * Disposes of the gizmo
  97167. */
  97168. PlaneRotationGizmo.prototype.dispose = function () {
  97169. this.onSnapObservable.clear();
  97170. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97171. this.dragBehavior.detach();
  97172. _super.prototype.dispose.call(this);
  97173. };
  97174. return PlaneRotationGizmo;
  97175. }(BABYLON.Gizmo));
  97176. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  97177. })(BABYLON || (BABYLON = {}));
  97178. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  97179. var BABYLON;
  97180. (function (BABYLON) {
  97181. /**
  97182. * Gizmo that enables dragging a mesh along 3 axis
  97183. */
  97184. var PositionGizmo = /** @class */ (function (_super) {
  97185. __extends(PositionGizmo, _super);
  97186. /**
  97187. * Creates a PositionGizmo
  97188. * @param gizmoLayer The utility layer the gizmo will be added to
  97189. */
  97190. function PositionGizmo(gizmoLayer) {
  97191. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97192. var _this = _super.call(this, gizmoLayer) || this;
  97193. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97194. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97195. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97196. _this.attachedMesh = null;
  97197. return _this;
  97198. }
  97199. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  97200. set: function (mesh) {
  97201. if (this.xGizmo) {
  97202. this.xGizmo.attachedMesh = mesh;
  97203. this.yGizmo.attachedMesh = mesh;
  97204. this.zGizmo.attachedMesh = mesh;
  97205. }
  97206. },
  97207. enumerable: true,
  97208. configurable: true
  97209. });
  97210. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97211. get: function () {
  97212. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97213. },
  97214. set: function (value) {
  97215. if (this.xGizmo) {
  97216. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97217. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97218. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97219. }
  97220. },
  97221. enumerable: true,
  97222. configurable: true
  97223. });
  97224. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  97225. get: function () {
  97226. return this.xGizmo.snapDistance;
  97227. },
  97228. /**
  97229. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97230. */
  97231. set: function (value) {
  97232. if (this.xGizmo) {
  97233. this.xGizmo.snapDistance = value;
  97234. this.yGizmo.snapDistance = value;
  97235. this.zGizmo.snapDistance = value;
  97236. }
  97237. },
  97238. enumerable: true,
  97239. configurable: true
  97240. });
  97241. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  97242. get: function () {
  97243. return this.xGizmo.scaleRatio;
  97244. },
  97245. /**
  97246. * Ratio for the scale of the gizmo (Default: 1)
  97247. */
  97248. set: function (value) {
  97249. if (this.xGizmo) {
  97250. this.xGizmo.scaleRatio = value;
  97251. this.yGizmo.scaleRatio = value;
  97252. this.zGizmo.scaleRatio = value;
  97253. }
  97254. },
  97255. enumerable: true,
  97256. configurable: true
  97257. });
  97258. /**
  97259. * Disposes of the gizmo
  97260. */
  97261. PositionGizmo.prototype.dispose = function () {
  97262. this.xGizmo.dispose();
  97263. this.yGizmo.dispose();
  97264. this.zGizmo.dispose();
  97265. };
  97266. /**
  97267. * CustomMeshes are not supported by this gizmo
  97268. * @param mesh The mesh to replace the default mesh of the gizmo
  97269. */
  97270. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  97271. 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)");
  97272. };
  97273. return PositionGizmo;
  97274. }(BABYLON.Gizmo));
  97275. BABYLON.PositionGizmo = PositionGizmo;
  97276. })(BABYLON || (BABYLON = {}));
  97277. //# sourceMappingURL=babylon.positionGizmo.js.map
  97278. var BABYLON;
  97279. (function (BABYLON) {
  97280. /**
  97281. * Gizmo that enables rotating a mesh along 3 axis
  97282. */
  97283. var RotationGizmo = /** @class */ (function (_super) {
  97284. __extends(RotationGizmo, _super);
  97285. /**
  97286. * Creates a RotationGizmo
  97287. * @param gizmoLayer The utility layer the gizmo will be added to
  97288. */
  97289. function RotationGizmo(gizmoLayer) {
  97290. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97291. var _this = _super.call(this, gizmoLayer) || this;
  97292. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97293. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97294. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97295. _this.attachedMesh = null;
  97296. return _this;
  97297. }
  97298. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  97299. set: function (mesh) {
  97300. if (this.xGizmo) {
  97301. this.xGizmo.attachedMesh = mesh;
  97302. this.yGizmo.attachedMesh = mesh;
  97303. this.zGizmo.attachedMesh = mesh;
  97304. }
  97305. },
  97306. enumerable: true,
  97307. configurable: true
  97308. });
  97309. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97310. get: function () {
  97311. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97312. },
  97313. set: function (value) {
  97314. if (this.xGizmo) {
  97315. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97316. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97317. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97318. }
  97319. },
  97320. enumerable: true,
  97321. configurable: true
  97322. });
  97323. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  97324. get: function () {
  97325. return this.xGizmo.snapDistance;
  97326. },
  97327. /**
  97328. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97329. */
  97330. set: function (value) {
  97331. if (this.xGizmo) {
  97332. this.xGizmo.snapDistance = value;
  97333. this.yGizmo.snapDistance = value;
  97334. this.zGizmo.snapDistance = value;
  97335. }
  97336. },
  97337. enumerable: true,
  97338. configurable: true
  97339. });
  97340. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  97341. get: function () {
  97342. return this.xGizmo.scaleRatio;
  97343. },
  97344. /**
  97345. * Ratio for the scale of the gizmo (Default: 1)
  97346. */
  97347. set: function (value) {
  97348. if (this.xGizmo) {
  97349. this.xGizmo.scaleRatio = value;
  97350. this.yGizmo.scaleRatio = value;
  97351. this.zGizmo.scaleRatio = value;
  97352. }
  97353. },
  97354. enumerable: true,
  97355. configurable: true
  97356. });
  97357. /**
  97358. * Disposes of the gizmo
  97359. */
  97360. RotationGizmo.prototype.dispose = function () {
  97361. this.xGizmo.dispose();
  97362. this.yGizmo.dispose();
  97363. this.zGizmo.dispose();
  97364. };
  97365. /**
  97366. * CustomMeshes are not supported by this gizmo
  97367. * @param mesh The mesh to replace the default mesh of the gizmo
  97368. */
  97369. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  97370. 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)");
  97371. };
  97372. return RotationGizmo;
  97373. }(BABYLON.Gizmo));
  97374. BABYLON.RotationGizmo = RotationGizmo;
  97375. })(BABYLON || (BABYLON = {}));
  97376. //# sourceMappingURL=babylon.rotationGizmo.js.map
  97377. var BABYLON;
  97378. (function (BABYLON) {
  97379. /**
  97380. * Gizmo that enables scaling a mesh along 3 axis
  97381. */
  97382. var ScaleGizmo = /** @class */ (function (_super) {
  97383. __extends(ScaleGizmo, _super);
  97384. /**
  97385. * Creates a ScaleGizmo
  97386. * @param gizmoLayer The utility layer the gizmo will be added to
  97387. */
  97388. function ScaleGizmo(gizmoLayer) {
  97389. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  97390. var _this = _super.call(this, gizmoLayer) || this;
  97391. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  97392. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  97393. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  97394. // Create uniform scale gizmo
  97395. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  97396. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97397. _this.uniformScaleGizmo.uniformScaling = true;
  97398. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  97399. octahedron.scaling.scaleInPlace(0.007);
  97400. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  97401. _this.attachedMesh = null;
  97402. return _this;
  97403. }
  97404. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  97405. set: function (mesh) {
  97406. if (this.xGizmo) {
  97407. this.xGizmo.attachedMesh = mesh;
  97408. this.yGizmo.attachedMesh = mesh;
  97409. this.zGizmo.attachedMesh = mesh;
  97410. this.uniformScaleGizmo.attachedMesh = mesh;
  97411. }
  97412. },
  97413. enumerable: true,
  97414. configurable: true
  97415. });
  97416. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  97417. get: function () {
  97418. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  97419. },
  97420. set: function (value) {
  97421. if (this.xGizmo) {
  97422. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97423. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97424. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  97425. }
  97426. },
  97427. enumerable: true,
  97428. configurable: true
  97429. });
  97430. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  97431. get: function () {
  97432. return this.xGizmo.snapDistance;
  97433. },
  97434. /**
  97435. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  97436. */
  97437. set: function (value) {
  97438. if (this.xGizmo) {
  97439. this.xGizmo.snapDistance = value;
  97440. this.yGizmo.snapDistance = value;
  97441. this.zGizmo.snapDistance = value;
  97442. this.uniformScaleGizmo.snapDistance = value;
  97443. }
  97444. },
  97445. enumerable: true,
  97446. configurable: true
  97447. });
  97448. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  97449. get: function () {
  97450. return this.xGizmo.scaleRatio;
  97451. },
  97452. /**
  97453. * Ratio for the scale of the gizmo (Default: 1)
  97454. */
  97455. set: function (value) {
  97456. if (this.xGizmo) {
  97457. this.xGizmo.scaleRatio = value;
  97458. this.yGizmo.scaleRatio = value;
  97459. this.zGizmo.scaleRatio = value;
  97460. this.uniformScaleGizmo.scaleRatio = value;
  97461. }
  97462. },
  97463. enumerable: true,
  97464. configurable: true
  97465. });
  97466. /**
  97467. * Disposes of the gizmo
  97468. */
  97469. ScaleGizmo.prototype.dispose = function () {
  97470. this.xGizmo.dispose();
  97471. this.yGizmo.dispose();
  97472. this.zGizmo.dispose();
  97473. this.uniformScaleGizmo.dispose();
  97474. };
  97475. return ScaleGizmo;
  97476. }(BABYLON.Gizmo));
  97477. BABYLON.ScaleGizmo = ScaleGizmo;
  97478. })(BABYLON || (BABYLON = {}));
  97479. //# sourceMappingURL=babylon.scaleGizmo.js.map
  97480. var BABYLON;
  97481. (function (BABYLON) {
  97482. /**
  97483. * Bounding box gizmo
  97484. */
  97485. var BoundingBoxGizmo = /** @class */ (function (_super) {
  97486. __extends(BoundingBoxGizmo, _super);
  97487. /**
  97488. * Creates an BoundingBoxGizmo
  97489. * @param gizmoLayer The utility layer the gizmo will be added to
  97490. * @param color The color of the gizmo
  97491. */
  97492. function BoundingBoxGizmo(color, gizmoLayer) {
  97493. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  97494. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  97495. var _this = _super.call(this, gizmoLayer) || this;
  97496. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  97497. _this._renderObserver = null;
  97498. _this._pointerObserver = null;
  97499. _this._scaleDragSpeed = 0.2;
  97500. _this._tmpQuaternion = new BABYLON.Quaternion();
  97501. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97502. _this._tmpRotationMatrix = new BABYLON.Matrix();
  97503. /**
  97504. * 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)
  97505. */
  97506. _this.ignoreChildren = false;
  97507. /**
  97508. * 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)
  97509. */
  97510. _this.includeChildPredicate = null;
  97511. /**
  97512. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  97513. */
  97514. _this.rotationSphereSize = 0.1;
  97515. /**
  97516. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  97517. */
  97518. _this.scaleBoxSize = 0.1;
  97519. /**
  97520. * 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)
  97521. */
  97522. _this.fixedDragMeshScreenSize = false;
  97523. /**
  97524. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  97525. */
  97526. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  97527. /**
  97528. * Fired when a rotation sphere or scale box is dragged
  97529. */
  97530. _this.onDragStartObservable = new BABYLON.Observable();
  97531. /**
  97532. * Fired when a scale box is dragged
  97533. */
  97534. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  97535. /**
  97536. * Fired when a scale box drag is ended
  97537. */
  97538. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  97539. /**
  97540. * Fired when a rotation sphere is dragged
  97541. */
  97542. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  97543. /**
  97544. * Fired when a rotation sphere drag is ended
  97545. */
  97546. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  97547. /**
  97548. * 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)
  97549. */
  97550. _this.scalePivot = null;
  97551. _this._existingMeshScale = new BABYLON.Vector3();
  97552. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  97553. _this._updateScale = false;
  97554. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  97555. // Create Materials
  97556. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97557. coloredMaterial.disableLighting = true;
  97558. coloredMaterial.emissiveColor = color;
  97559. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  97560. hoverColoredMaterial.disableLighting = true;
  97561. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  97562. // Build bounding box out of lines
  97563. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97564. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  97565. var lines = [];
  97566. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  97567. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  97568. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  97569. 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));
  97570. 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));
  97571. 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));
  97572. 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));
  97573. 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));
  97574. 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));
  97575. 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));
  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, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  97577. 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));
  97578. lines.forEach(function (l) {
  97579. l.color = color;
  97580. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  97581. l.isPickable = false;
  97582. _this._lineBoundingBox.addChild(l);
  97583. });
  97584. _this._rootMesh.addChild(_this._lineBoundingBox);
  97585. // Create rotation spheres
  97586. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97587. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  97588. var _loop_1 = function (i_1) {
  97589. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  97590. sphere.rotationQuaternion = new BABYLON.Quaternion();
  97591. sphere.material = coloredMaterial;
  97592. // Drag behavior
  97593. _dragBehavior = new BABYLON.PointerDragBehavior({});
  97594. _dragBehavior.moveAttached = false;
  97595. _dragBehavior.updateDragPlane = false;
  97596. sphere.addBehavior(_dragBehavior);
  97597. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  97598. var totalTurnAmountOfDrag = 0;
  97599. _dragBehavior.onDragStartObservable.add(function (event) {
  97600. startingTurnDirection.copyFrom(sphere.forward);
  97601. totalTurnAmountOfDrag = 0;
  97602. });
  97603. _dragBehavior.onDragObservable.add(function (event) {
  97604. _this.onRotationSphereDragObservable.notifyObservers({});
  97605. if (_this.attachedMesh) {
  97606. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97607. var worldDragDirection = startingTurnDirection;
  97608. // Project the world right on to the drag plane
  97609. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  97610. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  97611. // project drag delta on to the resulting drag axis and rotate based on that
  97612. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  97613. // Make rotation relative to size of mesh.
  97614. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97615. // Rotate based on axis
  97616. if (!_this.attachedMesh.rotationQuaternion) {
  97617. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  97618. }
  97619. if (!_this._anchorMesh.rotationQuaternion) {
  97620. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  97621. }
  97622. // Do not allow the object to turn more than a full circle
  97623. totalTurnAmountOfDrag += projectDist;
  97624. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  97625. if (i_1 >= 8) {
  97626. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  97627. }
  97628. else if (i_1 >= 4) {
  97629. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  97630. }
  97631. else {
  97632. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  97633. }
  97634. // Rotate around center of bounding box
  97635. _this._anchorMesh.addChild(_this.attachedMesh);
  97636. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  97637. _this._anchorMesh.removeChild(_this.attachedMesh);
  97638. }
  97639. _this.updateBoundingBox();
  97640. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97641. }
  97642. });
  97643. // Selection/deselection
  97644. _dragBehavior.onDragStartObservable.add(function () {
  97645. _this.onDragStartObservable.notifyObservers({});
  97646. _this._selectNode(sphere);
  97647. });
  97648. _dragBehavior.onDragEndObservable.add(function () {
  97649. _this.onRotationSphereDragEndObservable.notifyObservers({});
  97650. _this._selectNode(null);
  97651. });
  97652. this_1._rotateSpheresParent.addChild(sphere);
  97653. };
  97654. var this_1 = this, _dragBehavior;
  97655. for (var i_1 = 0; i_1 < 12; i_1++) {
  97656. _loop_1(i_1);
  97657. }
  97658. _this._rootMesh.addChild(_this._rotateSpheresParent);
  97659. // Create scale cubes
  97660. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  97661. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  97662. for (var i = 0; i < 2; i++) {
  97663. for (var j = 0; j < 2; j++) {
  97664. var _loop_2 = function () {
  97665. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  97666. box.material = coloredMaterial;
  97667. // Dragging logic
  97668. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  97669. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  97670. _dragBehavior.moveAttached = false;
  97671. box.addBehavior(_dragBehavior);
  97672. _dragBehavior.onDragObservable.add(function (event) {
  97673. _this.onScaleBoxDragObservable.notifyObservers({});
  97674. if (_this.attachedMesh) {
  97675. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  97676. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  97677. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  97678. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  97679. _this.updateBoundingBox();
  97680. if (_this.scalePivot) {
  97681. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  97682. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  97683. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  97684. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97685. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97686. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  97687. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  97688. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  97689. }
  97690. else {
  97691. // Scale from the position of the opposite corner
  97692. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  97693. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  97694. }
  97695. _this._anchorMesh.addChild(_this.attachedMesh);
  97696. _this._anchorMesh.scaling.addInPlace(deltaScale);
  97697. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  97698. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  97699. }
  97700. _this._anchorMesh.removeChild(_this.attachedMesh);
  97701. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  97702. }
  97703. });
  97704. // Selection/deselection
  97705. _dragBehavior.onDragStartObservable.add(function () {
  97706. _this.onDragStartObservable.notifyObservers({});
  97707. _this._selectNode(box);
  97708. });
  97709. _dragBehavior.onDragEndObservable.add(function () {
  97710. _this.onScaleBoxDragEndObservable.notifyObservers({});
  97711. _this._selectNode(null);
  97712. });
  97713. this_2._scaleBoxesParent.addChild(box);
  97714. };
  97715. var this_2 = this, _dragBehavior;
  97716. for (var k = 0; k < 2; k++) {
  97717. _loop_2();
  97718. }
  97719. }
  97720. }
  97721. _this._rootMesh.addChild(_this._scaleBoxesParent);
  97722. // Hover color change
  97723. var pointerIds = new Array();
  97724. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  97725. if (!pointerIds[pointerInfo.event.pointerId]) {
  97726. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  97727. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  97728. pointerIds[pointerInfo.event.pointerId] = mesh;
  97729. mesh.material = hoverColoredMaterial;
  97730. }
  97731. });
  97732. }
  97733. else {
  97734. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  97735. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  97736. delete pointerIds[pointerInfo.event.pointerId];
  97737. }
  97738. }
  97739. });
  97740. // Update bounding box positions
  97741. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  97742. // Only update the bouding box if scaling has changed
  97743. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  97744. _this.updateBoundingBox();
  97745. }
  97746. });
  97747. _this.updateBoundingBox();
  97748. return _this;
  97749. }
  97750. /** @hidden */
  97751. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  97752. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  97753. // Save old pivot and set pivot to 0,0,0
  97754. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  97755. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  97756. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  97757. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  97758. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97759. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97760. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97761. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  97762. }
  97763. }
  97764. BoundingBoxGizmo._PivotCached++;
  97765. };
  97766. /** @hidden */
  97767. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  97768. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  97769. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  97770. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  97771. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  97772. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  97773. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  97774. }
  97775. this._PivotCached--;
  97776. };
  97777. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  97778. if (value) {
  97779. // Reset anchor mesh to match attached mesh's scale
  97780. // This is needed to avoid invalid box/sphere position on first drag
  97781. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  97782. this._anchorMesh.addChild(value);
  97783. this._anchorMesh.removeChild(value);
  97784. BoundingBoxGizmo._RestorePivotPoint(value);
  97785. this.updateBoundingBox();
  97786. }
  97787. };
  97788. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  97789. this._rotateSpheresParent.getChildMeshes()
  97790. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  97791. m.isVisible = (!selectedMesh || m == selectedMesh);
  97792. });
  97793. };
  97794. /**
  97795. * Updates the bounding box information for the Gizmo
  97796. */
  97797. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  97798. if (this.attachedMesh) {
  97799. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  97800. this._update();
  97801. // Rotate based on axis
  97802. if (!this.attachedMesh.rotationQuaternion) {
  97803. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  97804. }
  97805. if (!this._anchorMesh.rotationQuaternion) {
  97806. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  97807. }
  97808. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97809. // Store original position and reset mesh to origin before computing the bounding box
  97810. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  97811. this._tmpVector.copyFrom(this.attachedMesh.position);
  97812. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  97813. this.attachedMesh.position.set(0, 0, 0);
  97814. // Update bounding dimensions/positions
  97815. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  97816. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  97817. // Update gizmo to match bounding box scaling and rotation
  97818. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  97819. 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);
  97820. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  97821. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  97822. this._lineBoundingBox.computeWorldMatrix();
  97823. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  97824. // restore position/rotation values
  97825. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  97826. this.attachedMesh.position.copyFrom(this._tmpVector);
  97827. }
  97828. // Update rotation sphere locations
  97829. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  97830. for (var i = 0; i < 3; i++) {
  97831. for (var j = 0; j < 2; j++) {
  97832. for (var k = 0; k < 2; k++) {
  97833. var index = ((i * 4) + (j * 2)) + k;
  97834. if (i == 0) {
  97835. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97836. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97837. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97838. }
  97839. if (i == 1) {
  97840. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  97841. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97842. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97843. }
  97844. if (i == 2) {
  97845. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  97846. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97847. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  97848. }
  97849. if (this.fixedDragMeshScreenSize) {
  97850. this._rootMesh.computeWorldMatrix();
  97851. this._rotateSpheresParent.computeWorldMatrix();
  97852. rotateSpheres[index].computeWorldMatrix();
  97853. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97854. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97855. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97856. }
  97857. else {
  97858. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  97859. }
  97860. }
  97861. }
  97862. }
  97863. // Update scale box locations
  97864. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  97865. for (var i = 0; i < 2; i++) {
  97866. for (var j = 0; j < 2; j++) {
  97867. for (var k = 0; k < 2; k++) {
  97868. var index = ((i * 4) + (j * 2)) + k;
  97869. if (scaleBoxes[index]) {
  97870. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  97871. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  97872. if (this.fixedDragMeshScreenSize) {
  97873. this._rootMesh.computeWorldMatrix();
  97874. this._scaleBoxesParent.computeWorldMatrix();
  97875. scaleBoxes[index].computeWorldMatrix();
  97876. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  97877. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  97878. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  97879. }
  97880. else {
  97881. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  97882. }
  97883. }
  97884. }
  97885. }
  97886. }
  97887. if (this.attachedMesh) {
  97888. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  97889. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  97890. }
  97891. };
  97892. /**
  97893. * Enables rotation on the specified axis and disables rotation on the others
  97894. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  97895. */
  97896. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  97897. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  97898. if (i < 4) {
  97899. m.setEnabled(axis.indexOf("x") != -1);
  97900. }
  97901. else if (i < 8) {
  97902. m.setEnabled(axis.indexOf("y") != -1);
  97903. }
  97904. else {
  97905. m.setEnabled(axis.indexOf("z") != -1);
  97906. }
  97907. });
  97908. };
  97909. /**
  97910. * Disposes of the gizmo
  97911. */
  97912. BoundingBoxGizmo.prototype.dispose = function () {
  97913. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  97914. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  97915. this._lineBoundingBox.dispose();
  97916. this._rotateSpheresParent.dispose();
  97917. this._scaleBoxesParent.dispose();
  97918. _super.prototype.dispose.call(this);
  97919. };
  97920. /**
  97921. * 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)
  97922. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  97923. * @returns the bounding box mesh with the passed in mesh as a child
  97924. */
  97925. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  97926. var makeNotPickable = function (root) {
  97927. root.isPickable = false;
  97928. root.getChildMeshes().forEach(function (c) {
  97929. makeNotPickable(c);
  97930. });
  97931. };
  97932. makeNotPickable(mesh);
  97933. // Reset position to get boudning box from origin with no rotation
  97934. if (!mesh.rotationQuaternion) {
  97935. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  97936. }
  97937. var oldPos = mesh.position.clone();
  97938. var oldRot = mesh.rotationQuaternion.clone();
  97939. mesh.rotationQuaternion.set(0, 0, 0, 1);
  97940. mesh.position.set(0, 0, 0);
  97941. // Update bounding dimensions/positions
  97942. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  97943. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  97944. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  97945. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  97946. // Restore original positions
  97947. mesh.addChild(box);
  97948. mesh.rotationQuaternion.copyFrom(oldRot);
  97949. mesh.position.copyFrom(oldPos);
  97950. // Reverse parenting
  97951. mesh.removeChild(box);
  97952. box.addChild(mesh);
  97953. box.visibility = 0;
  97954. return box;
  97955. };
  97956. /**
  97957. * CustomMeshes are not supported by this gizmo
  97958. * @param mesh The mesh to replace the default mesh of the gizmo
  97959. */
  97960. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  97961. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  97962. };
  97963. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  97964. // store/remove pivot point should only be applied during their outermost calls
  97965. BoundingBoxGizmo._PivotCached = 0;
  97966. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  97967. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  97968. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  97969. return BoundingBoxGizmo;
  97970. }(BABYLON.Gizmo));
  97971. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  97972. })(BABYLON || (BABYLON = {}));
  97973. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  97974. var BABYLON;
  97975. (function (BABYLON) {
  97976. /**
  97977. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  97978. */
  97979. var GizmoManager = /** @class */ (function () {
  97980. /**
  97981. * Instatiates a gizmo manager
  97982. * @param scene the scene to overlay the gizmos on top of
  97983. */
  97984. function GizmoManager(scene) {
  97985. var _this = this;
  97986. this.scene = scene;
  97987. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  97988. this._pointerObserver = null;
  97989. this._attachedMesh = null;
  97990. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  97991. /**
  97992. * When bounding box gizmo is enabled, this can be used to track drag/end events
  97993. */
  97994. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  97995. /**
  97996. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  97997. */
  97998. this.attachableMeshes = null;
  97999. /**
  98000. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  98001. */
  98002. this.usePointerToAttachGizmos = true;
  98003. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  98004. // Instatiate/dispose gizmos based on pointer actions
  98005. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  98006. if (!_this.usePointerToAttachGizmos) {
  98007. return;
  98008. }
  98009. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98010. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  98011. var node = pointerInfo.pickInfo.pickedMesh;
  98012. if (_this.attachableMeshes == null) {
  98013. // Attach to the most parent node
  98014. while (node && node.parent != null) {
  98015. node = node.parent;
  98016. }
  98017. }
  98018. else {
  98019. // Attach to the parent node that is an attachableMesh
  98020. var found = false;
  98021. _this.attachableMeshes.forEach(function (mesh) {
  98022. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  98023. node = mesh;
  98024. found = true;
  98025. }
  98026. });
  98027. if (!found) {
  98028. node = null;
  98029. }
  98030. }
  98031. if (node instanceof BABYLON.AbstractMesh) {
  98032. _this.attachToMesh(node);
  98033. }
  98034. else {
  98035. _this.attachToMesh(null);
  98036. }
  98037. }
  98038. else {
  98039. _this.attachToMesh(null);
  98040. }
  98041. }
  98042. });
  98043. }
  98044. /**
  98045. * Attaches a set of gizmos to the specified mesh
  98046. * @param mesh The mesh the gizmo's should be attached to
  98047. */
  98048. GizmoManager.prototype.attachToMesh = function (mesh) {
  98049. if (this._attachedMesh) {
  98050. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98051. }
  98052. this._attachedMesh = mesh;
  98053. for (var key in this.gizmos) {
  98054. var gizmo = (this.gizmos[key]);
  98055. if (gizmo && this._gizmosEnabled[key]) {
  98056. gizmo.attachedMesh = mesh;
  98057. }
  98058. }
  98059. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  98060. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98061. }
  98062. };
  98063. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  98064. get: function () {
  98065. return this._gizmosEnabled.positionGizmo;
  98066. },
  98067. /**
  98068. * If the position gizmo is enabled
  98069. */
  98070. set: function (value) {
  98071. if (value) {
  98072. if (!this.gizmos.positionGizmo) {
  98073. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  98074. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98075. }
  98076. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  98077. }
  98078. else if (this.gizmos.positionGizmo) {
  98079. this.gizmos.positionGizmo.attachedMesh = null;
  98080. }
  98081. this._gizmosEnabled.positionGizmo = value;
  98082. },
  98083. enumerable: true,
  98084. configurable: true
  98085. });
  98086. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  98087. get: function () {
  98088. return this._gizmosEnabled.rotationGizmo;
  98089. },
  98090. /**
  98091. * If the rotation gizmo is enabled
  98092. */
  98093. set: function (value) {
  98094. if (value) {
  98095. if (!this.gizmos.rotationGizmo) {
  98096. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  98097. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  98098. }
  98099. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  98100. }
  98101. else if (this.gizmos.rotationGizmo) {
  98102. this.gizmos.rotationGizmo.attachedMesh = null;
  98103. }
  98104. this._gizmosEnabled.rotationGizmo = value;
  98105. },
  98106. enumerable: true,
  98107. configurable: true
  98108. });
  98109. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  98110. get: function () {
  98111. return this._gizmosEnabled.scaleGizmo;
  98112. },
  98113. /**
  98114. * If the scale gizmo is enabled
  98115. */
  98116. set: function (value) {
  98117. if (value) {
  98118. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  98119. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  98120. }
  98121. else if (this.gizmos.scaleGizmo) {
  98122. this.gizmos.scaleGizmo.attachedMesh = null;
  98123. }
  98124. this._gizmosEnabled.scaleGizmo = value;
  98125. },
  98126. enumerable: true,
  98127. configurable: true
  98128. });
  98129. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  98130. get: function () {
  98131. return this._gizmosEnabled.boundingBoxGizmo;
  98132. },
  98133. /**
  98134. * If the boundingBox gizmo is enabled
  98135. */
  98136. set: function (value) {
  98137. if (value) {
  98138. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  98139. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  98140. if (this._attachedMesh) {
  98141. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  98142. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  98143. }
  98144. }
  98145. else if (this.gizmos.boundingBoxGizmo) {
  98146. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  98147. }
  98148. this._gizmosEnabled.boundingBoxGizmo = value;
  98149. },
  98150. enumerable: true,
  98151. configurable: true
  98152. });
  98153. /**
  98154. * Disposes of the gizmo manager
  98155. */
  98156. GizmoManager.prototype.dispose = function () {
  98157. this.scene.onPointerObservable.remove(this._pointerObserver);
  98158. for (var key in this.gizmos) {
  98159. var gizmo = (this.gizmos[key]);
  98160. if (gizmo) {
  98161. gizmo.dispose();
  98162. }
  98163. }
  98164. this.boundingBoxDragBehavior.detach();
  98165. };
  98166. return GizmoManager;
  98167. }());
  98168. BABYLON.GizmoManager = GizmoManager;
  98169. })(BABYLON || (BABYLON = {}));
  98170. //# sourceMappingURL=babylon.gizmoManager.js.map
  98171. var BABYLON;
  98172. (function (BABYLON) {
  98173. /**
  98174. * Defines a target to use with MorphTargetManager
  98175. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98176. */
  98177. var MorphTarget = /** @class */ (function () {
  98178. /**
  98179. * Creates a new MorphTarget
  98180. * @param name defines the name of the target
  98181. * @param influence defines the influence to use
  98182. */
  98183. function MorphTarget(
  98184. /** defines the name of the target */
  98185. name, influence, scene) {
  98186. if (influence === void 0) { influence = 0; }
  98187. if (scene === void 0) { scene = null; }
  98188. this.name = name;
  98189. /**
  98190. * Gets or sets the list of animations
  98191. */
  98192. this.animations = new Array();
  98193. this._positions = null;
  98194. this._normals = null;
  98195. this._tangents = null;
  98196. /**
  98197. * Observable raised when the influence changes
  98198. */
  98199. this.onInfluenceChanged = new BABYLON.Observable();
  98200. this._animationPropertiesOverride = null;
  98201. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98202. this.influence = influence;
  98203. }
  98204. Object.defineProperty(MorphTarget.prototype, "influence", {
  98205. /**
  98206. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  98207. */
  98208. get: function () {
  98209. return this._influence;
  98210. },
  98211. set: function (influence) {
  98212. if (this._influence === influence) {
  98213. return;
  98214. }
  98215. var previous = this._influence;
  98216. this._influence = influence;
  98217. if (this.onInfluenceChanged.hasObservers) {
  98218. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  98219. }
  98220. },
  98221. enumerable: true,
  98222. configurable: true
  98223. });
  98224. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  98225. /**
  98226. * Gets or sets the animation properties override
  98227. */
  98228. get: function () {
  98229. if (!this._animationPropertiesOverride && this._scene) {
  98230. return this._scene.animationPropertiesOverride;
  98231. }
  98232. return this._animationPropertiesOverride;
  98233. },
  98234. set: function (value) {
  98235. this._animationPropertiesOverride = value;
  98236. },
  98237. enumerable: true,
  98238. configurable: true
  98239. });
  98240. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  98241. /**
  98242. * Gets a boolean defining if the target contains position data
  98243. */
  98244. get: function () {
  98245. return !!this._positions;
  98246. },
  98247. enumerable: true,
  98248. configurable: true
  98249. });
  98250. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  98251. /**
  98252. * Gets a boolean defining if the target contains normal data
  98253. */
  98254. get: function () {
  98255. return !!this._normals;
  98256. },
  98257. enumerable: true,
  98258. configurable: true
  98259. });
  98260. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  98261. /**
  98262. * Gets a boolean defining if the target contains tangent data
  98263. */
  98264. get: function () {
  98265. return !!this._tangents;
  98266. },
  98267. enumerable: true,
  98268. configurable: true
  98269. });
  98270. /**
  98271. * Affects position data to this target
  98272. * @param data defines the position data to use
  98273. */
  98274. MorphTarget.prototype.setPositions = function (data) {
  98275. this._positions = data;
  98276. };
  98277. /**
  98278. * Gets the position data stored in this target
  98279. * @returns a FloatArray containing the position data (or null if not present)
  98280. */
  98281. MorphTarget.prototype.getPositions = function () {
  98282. return this._positions;
  98283. };
  98284. /**
  98285. * Affects normal data to this target
  98286. * @param data defines the normal data to use
  98287. */
  98288. MorphTarget.prototype.setNormals = function (data) {
  98289. this._normals = data;
  98290. };
  98291. /**
  98292. * Gets the normal data stored in this target
  98293. * @returns a FloatArray containing the normal data (or null if not present)
  98294. */
  98295. MorphTarget.prototype.getNormals = function () {
  98296. return this._normals;
  98297. };
  98298. /**
  98299. * Affects tangent data to this target
  98300. * @param data defines the tangent data to use
  98301. */
  98302. MorphTarget.prototype.setTangents = function (data) {
  98303. this._tangents = data;
  98304. };
  98305. /**
  98306. * Gets the tangent data stored in this target
  98307. * @returns a FloatArray containing the tangent data (or null if not present)
  98308. */
  98309. MorphTarget.prototype.getTangents = function () {
  98310. return this._tangents;
  98311. };
  98312. /**
  98313. * Serializes the current target into a Serialization object
  98314. * @returns the serialized object
  98315. */
  98316. MorphTarget.prototype.serialize = function () {
  98317. var serializationObject = {};
  98318. serializationObject.name = this.name;
  98319. serializationObject.influence = this.influence;
  98320. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  98321. if (this.hasNormals) {
  98322. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  98323. }
  98324. if (this.hasTangents) {
  98325. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  98326. }
  98327. // Animations
  98328. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  98329. return serializationObject;
  98330. };
  98331. // Statics
  98332. /**
  98333. * Creates a new target from serialized data
  98334. * @param serializationObject defines the serialized data to use
  98335. * @returns a new MorphTarget
  98336. */
  98337. MorphTarget.Parse = function (serializationObject) {
  98338. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  98339. result.setPositions(serializationObject.positions);
  98340. if (serializationObject.normals) {
  98341. result.setNormals(serializationObject.normals);
  98342. }
  98343. if (serializationObject.tangents) {
  98344. result.setTangents(serializationObject.tangents);
  98345. }
  98346. // Animations
  98347. if (serializationObject.animations) {
  98348. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  98349. var parsedAnimation = serializationObject.animations[animationIndex];
  98350. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  98351. }
  98352. }
  98353. return result;
  98354. };
  98355. /**
  98356. * Creates a MorphTarget from mesh data
  98357. * @param mesh defines the source mesh
  98358. * @param name defines the name to use for the new target
  98359. * @param influence defines the influence to attach to the target
  98360. * @returns a new MorphTarget
  98361. */
  98362. MorphTarget.FromMesh = function (mesh, name, influence) {
  98363. if (!name) {
  98364. name = mesh.name;
  98365. }
  98366. var result = new MorphTarget(name, influence, mesh.getScene());
  98367. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  98368. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98369. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  98370. }
  98371. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  98372. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  98373. }
  98374. return result;
  98375. };
  98376. return MorphTarget;
  98377. }());
  98378. BABYLON.MorphTarget = MorphTarget;
  98379. })(BABYLON || (BABYLON = {}));
  98380. //# sourceMappingURL=babylon.morphTarget.js.map
  98381. var BABYLON;
  98382. (function (BABYLON) {
  98383. /**
  98384. * This class is used to deform meshes using morphing between different targets
  98385. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  98386. */
  98387. var MorphTargetManager = /** @class */ (function () {
  98388. /**
  98389. * Creates a new MorphTargetManager
  98390. * @param scene defines the current scene
  98391. */
  98392. function MorphTargetManager(scene) {
  98393. if (scene === void 0) { scene = null; }
  98394. this._targets = new Array();
  98395. this._targetObservable = new Array();
  98396. this._activeTargets = new BABYLON.SmartArray(16);
  98397. this._supportsNormals = false;
  98398. this._supportsTangents = false;
  98399. this._vertexCount = 0;
  98400. this._uniqueId = 0;
  98401. this._tempInfluences = new Array();
  98402. if (!scene) {
  98403. scene = BABYLON.Engine.LastCreatedScene;
  98404. }
  98405. this._scene = scene;
  98406. if (this._scene) {
  98407. this._scene.morphTargetManagers.push(this);
  98408. this._uniqueId = this._scene.getUniqueId();
  98409. }
  98410. }
  98411. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  98412. /**
  98413. * Gets the unique ID of this manager
  98414. */
  98415. get: function () {
  98416. return this._uniqueId;
  98417. },
  98418. enumerable: true,
  98419. configurable: true
  98420. });
  98421. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  98422. /**
  98423. * Gets the number of vertices handled by this manager
  98424. */
  98425. get: function () {
  98426. return this._vertexCount;
  98427. },
  98428. enumerable: true,
  98429. configurable: true
  98430. });
  98431. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  98432. /**
  98433. * Gets a boolean indicating if this manager supports morphing of normals
  98434. */
  98435. get: function () {
  98436. return this._supportsNormals;
  98437. },
  98438. enumerable: true,
  98439. configurable: true
  98440. });
  98441. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  98442. /**
  98443. * Gets a boolean indicating if this manager supports morphing of tangents
  98444. */
  98445. get: function () {
  98446. return this._supportsTangents;
  98447. },
  98448. enumerable: true,
  98449. configurable: true
  98450. });
  98451. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  98452. /**
  98453. * Gets the number of targets stored in this manager
  98454. */
  98455. get: function () {
  98456. return this._targets.length;
  98457. },
  98458. enumerable: true,
  98459. configurable: true
  98460. });
  98461. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  98462. /**
  98463. * Gets the number of influencers (ie. the number of targets with influences > 0)
  98464. */
  98465. get: function () {
  98466. return this._activeTargets.length;
  98467. },
  98468. enumerable: true,
  98469. configurable: true
  98470. });
  98471. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  98472. /**
  98473. * Gets the list of influences (one per target)
  98474. */
  98475. get: function () {
  98476. return this._influences;
  98477. },
  98478. enumerable: true,
  98479. configurable: true
  98480. });
  98481. /**
  98482. * Gets the active target at specified index. An active target is a target with an influence > 0
  98483. * @param index defines the index to check
  98484. * @returns the requested target
  98485. */
  98486. MorphTargetManager.prototype.getActiveTarget = function (index) {
  98487. return this._activeTargets.data[index];
  98488. };
  98489. /**
  98490. * Gets the target at specified index
  98491. * @param index defines the index to check
  98492. * @returns the requested target
  98493. */
  98494. MorphTargetManager.prototype.getTarget = function (index) {
  98495. return this._targets[index];
  98496. };
  98497. /**
  98498. * Add a new target to this manager
  98499. * @param target defines the target to add
  98500. */
  98501. MorphTargetManager.prototype.addTarget = function (target) {
  98502. var _this = this;
  98503. this._targets.push(target);
  98504. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  98505. _this._syncActiveTargets(needUpdate);
  98506. }));
  98507. this._syncActiveTargets(true);
  98508. };
  98509. /**
  98510. * Removes a target from the manager
  98511. * @param target defines the target to remove
  98512. */
  98513. MorphTargetManager.prototype.removeTarget = function (target) {
  98514. var index = this._targets.indexOf(target);
  98515. if (index >= 0) {
  98516. this._targets.splice(index, 1);
  98517. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  98518. this._syncActiveTargets(true);
  98519. }
  98520. };
  98521. /**
  98522. * Serializes the current manager into a Serialization object
  98523. * @returns the serialized object
  98524. */
  98525. MorphTargetManager.prototype.serialize = function () {
  98526. var serializationObject = {};
  98527. serializationObject.id = this.uniqueId;
  98528. serializationObject.targets = [];
  98529. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98530. var target = _a[_i];
  98531. serializationObject.targets.push(target.serialize());
  98532. }
  98533. return serializationObject;
  98534. };
  98535. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  98536. var influenceCount = 0;
  98537. this._activeTargets.reset();
  98538. this._supportsNormals = true;
  98539. this._supportsTangents = true;
  98540. this._vertexCount = 0;
  98541. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  98542. var target = _a[_i];
  98543. this._activeTargets.push(target);
  98544. this._tempInfluences[influenceCount++] = target.influence;
  98545. var positions = target.getPositions();
  98546. if (positions) {
  98547. this._supportsNormals = this._supportsNormals && target.hasNormals;
  98548. this._supportsTangents = this._supportsTangents && target.hasTangents;
  98549. var vertexCount = positions.length / 3;
  98550. if (this._vertexCount === 0) {
  98551. this._vertexCount = vertexCount;
  98552. }
  98553. else if (this._vertexCount !== vertexCount) {
  98554. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  98555. return;
  98556. }
  98557. }
  98558. }
  98559. if (!this._influences || this._influences.length !== influenceCount) {
  98560. this._influences = new Float32Array(influenceCount);
  98561. }
  98562. for (var index = 0; index < influenceCount; index++) {
  98563. this._influences[index] = this._tempInfluences[index];
  98564. }
  98565. if (needUpdate) {
  98566. this.synchronize();
  98567. }
  98568. };
  98569. /**
  98570. * Syncrhonize the targets with all the meshes using this morph target manager
  98571. */
  98572. MorphTargetManager.prototype.synchronize = function () {
  98573. if (!this._scene) {
  98574. return;
  98575. }
  98576. // Flag meshes as dirty to resync with the active targets
  98577. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  98578. var mesh = _a[_i];
  98579. if (mesh.morphTargetManager === this) {
  98580. mesh._syncGeometryWithMorphTargetManager();
  98581. }
  98582. }
  98583. };
  98584. // Statics
  98585. /**
  98586. * Creates a new MorphTargetManager from serialized data
  98587. * @param serializationObject defines the serialized data
  98588. * @param scene defines the hosting scene
  98589. * @returns the new MorphTargetManager
  98590. */
  98591. MorphTargetManager.Parse = function (serializationObject, scene) {
  98592. var result = new MorphTargetManager(scene);
  98593. result._uniqueId = serializationObject.id;
  98594. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  98595. var targetData = _a[_i];
  98596. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  98597. }
  98598. return result;
  98599. };
  98600. return MorphTargetManager;
  98601. }());
  98602. BABYLON.MorphTargetManager = MorphTargetManager;
  98603. })(BABYLON || (BABYLON = {}));
  98604. //# sourceMappingURL=babylon.morphTargetManager.js.map
  98605. var BABYLON;
  98606. (function (BABYLON) {
  98607. var Octree = /** @class */ (function () {
  98608. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  98609. if (maxDepth === void 0) { maxDepth = 2; }
  98610. this.maxDepth = maxDepth;
  98611. this.dynamicContent = new Array();
  98612. this._maxBlockCapacity = maxBlockCapacity || 64;
  98613. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  98614. this._creationFunc = creationFunc;
  98615. }
  98616. // Methods
  98617. Octree.prototype.update = function (worldMin, worldMax, entries) {
  98618. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  98619. };
  98620. Octree.prototype.addMesh = function (entry) {
  98621. for (var index = 0; index < this.blocks.length; index++) {
  98622. var block = this.blocks[index];
  98623. block.addEntry(entry);
  98624. }
  98625. };
  98626. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  98627. this._selectionContent.reset();
  98628. for (var index = 0; index < this.blocks.length; index++) {
  98629. var block = this.blocks[index];
  98630. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  98631. }
  98632. if (allowDuplicate) {
  98633. this._selectionContent.concat(this.dynamicContent);
  98634. }
  98635. else {
  98636. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98637. }
  98638. return this._selectionContent;
  98639. };
  98640. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  98641. this._selectionContent.reset();
  98642. for (var index = 0; index < this.blocks.length; index++) {
  98643. var block = this.blocks[index];
  98644. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  98645. }
  98646. if (allowDuplicate) {
  98647. this._selectionContent.concat(this.dynamicContent);
  98648. }
  98649. else {
  98650. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98651. }
  98652. return this._selectionContent;
  98653. };
  98654. Octree.prototype.intersectsRay = function (ray) {
  98655. this._selectionContent.reset();
  98656. for (var index = 0; index < this.blocks.length; index++) {
  98657. var block = this.blocks[index];
  98658. block.intersectsRay(ray, this._selectionContent);
  98659. }
  98660. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  98661. return this._selectionContent;
  98662. };
  98663. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  98664. target.blocks = new Array();
  98665. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  98666. // Segmenting space
  98667. for (var x = 0; x < 2; x++) {
  98668. for (var y = 0; y < 2; y++) {
  98669. for (var z = 0; z < 2; z++) {
  98670. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  98671. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  98672. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  98673. block.addEntries(entries);
  98674. target.blocks.push(block);
  98675. }
  98676. }
  98677. }
  98678. };
  98679. Octree.CreationFuncForMeshes = function (entry, block) {
  98680. var boundingInfo = entry.getBoundingInfo();
  98681. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98682. block.entries.push(entry);
  98683. }
  98684. };
  98685. Octree.CreationFuncForSubMeshes = function (entry, block) {
  98686. var boundingInfo = entry.getBoundingInfo();
  98687. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  98688. block.entries.push(entry);
  98689. }
  98690. };
  98691. return Octree;
  98692. }());
  98693. BABYLON.Octree = Octree;
  98694. })(BABYLON || (BABYLON = {}));
  98695. //# sourceMappingURL=babylon.octree.js.map
  98696. var BABYLON;
  98697. (function (BABYLON) {
  98698. /**
  98699. * Class used to store a cell in an octree
  98700. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98701. */
  98702. var OctreeBlock = /** @class */ (function () {
  98703. /**
  98704. * Creates a new block
  98705. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  98706. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  98707. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98708. * @param depth defines the current depth of this block in the octree
  98709. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  98710. * @param creationFunc defines a callback to call when an element is added to the block
  98711. */
  98712. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  98713. /**
  98714. * Gets the content of the current block
  98715. */
  98716. this.entries = new Array();
  98717. this._boundingVectors = new Array();
  98718. this._capacity = capacity;
  98719. this._depth = depth;
  98720. this._maxDepth = maxDepth;
  98721. this._creationFunc = creationFunc;
  98722. this._minPoint = minPoint;
  98723. this._maxPoint = maxPoint;
  98724. this._boundingVectors.push(minPoint.clone());
  98725. this._boundingVectors.push(maxPoint.clone());
  98726. this._boundingVectors.push(minPoint.clone());
  98727. this._boundingVectors[2].x = maxPoint.x;
  98728. this._boundingVectors.push(minPoint.clone());
  98729. this._boundingVectors[3].y = maxPoint.y;
  98730. this._boundingVectors.push(minPoint.clone());
  98731. this._boundingVectors[4].z = maxPoint.z;
  98732. this._boundingVectors.push(maxPoint.clone());
  98733. this._boundingVectors[5].z = minPoint.z;
  98734. this._boundingVectors.push(maxPoint.clone());
  98735. this._boundingVectors[6].x = minPoint.x;
  98736. this._boundingVectors.push(maxPoint.clone());
  98737. this._boundingVectors[7].y = minPoint.y;
  98738. }
  98739. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  98740. // Property
  98741. /**
  98742. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  98743. */
  98744. get: function () {
  98745. return this._capacity;
  98746. },
  98747. enumerable: true,
  98748. configurable: true
  98749. });
  98750. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  98751. /**
  98752. * Gets the minimum vector (in world space) of the block's bounding box
  98753. */
  98754. get: function () {
  98755. return this._minPoint;
  98756. },
  98757. enumerable: true,
  98758. configurable: true
  98759. });
  98760. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  98761. /**
  98762. * Gets the maximum vector (in world space) of the block's bounding box
  98763. */
  98764. get: function () {
  98765. return this._maxPoint;
  98766. },
  98767. enumerable: true,
  98768. configurable: true
  98769. });
  98770. // Methods
  98771. /**
  98772. * Add a new element to this block
  98773. * @param entry defines the element to add
  98774. */
  98775. OctreeBlock.prototype.addEntry = function (entry) {
  98776. if (this.blocks) {
  98777. for (var index = 0; index < this.blocks.length; index++) {
  98778. var block = this.blocks[index];
  98779. block.addEntry(entry);
  98780. }
  98781. return;
  98782. }
  98783. this._creationFunc(entry, this);
  98784. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  98785. this.createInnerBlocks();
  98786. }
  98787. };
  98788. /**
  98789. * Add an array of elements to this block
  98790. * @param entries defines the array of elements to add
  98791. */
  98792. OctreeBlock.prototype.addEntries = function (entries) {
  98793. for (var index = 0; index < entries.length; index++) {
  98794. var mesh = entries[index];
  98795. this.addEntry(mesh);
  98796. }
  98797. };
  98798. /**
  98799. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  98800. * @param frustumPlanes defines the frustum planes to test
  98801. * @param selection defines the array to store current content if selection is positive
  98802. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98803. */
  98804. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  98805. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  98806. if (this.blocks) {
  98807. for (var index = 0; index < this.blocks.length; index++) {
  98808. var block = this.blocks[index];
  98809. block.select(frustumPlanes, selection, allowDuplicate);
  98810. }
  98811. return;
  98812. }
  98813. if (allowDuplicate) {
  98814. selection.concat(this.entries);
  98815. }
  98816. else {
  98817. selection.concatWithNoDuplicate(this.entries);
  98818. }
  98819. }
  98820. };
  98821. /**
  98822. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  98823. * @param sphereCenter defines the bounding sphere center
  98824. * @param sphereRadius defines the bounding sphere radius
  98825. * @param selection defines the array to store current content if selection is positive
  98826. * @param allowDuplicate defines if the selection array can contains duplicated entries
  98827. */
  98828. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  98829. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  98830. if (this.blocks) {
  98831. for (var index = 0; index < this.blocks.length; index++) {
  98832. var block = this.blocks[index];
  98833. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  98834. }
  98835. return;
  98836. }
  98837. if (allowDuplicate) {
  98838. selection.concat(this.entries);
  98839. }
  98840. else {
  98841. selection.concatWithNoDuplicate(this.entries);
  98842. }
  98843. }
  98844. };
  98845. /**
  98846. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  98847. * @param ray defines the ray to test with
  98848. * @param selection defines the array to store current content if selection is positive
  98849. */
  98850. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  98851. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  98852. if (this.blocks) {
  98853. for (var index = 0; index < this.blocks.length; index++) {
  98854. var block = this.blocks[index];
  98855. block.intersectsRay(ray, selection);
  98856. }
  98857. return;
  98858. }
  98859. selection.concatWithNoDuplicate(this.entries);
  98860. }
  98861. };
  98862. /**
  98863. * Subdivide the content into child blocks (this block will then be empty)
  98864. */
  98865. OctreeBlock.prototype.createInnerBlocks = function () {
  98866. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  98867. };
  98868. return OctreeBlock;
  98869. }());
  98870. BABYLON.OctreeBlock = OctreeBlock;
  98871. })(BABYLON || (BABYLON = {}));
  98872. //# sourceMappingURL=babylon.octreeBlock.js.map
  98873. var BABYLON;
  98874. (function (BABYLON) {
  98875. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  98876. if (maxCapacity === void 0) { maxCapacity = 64; }
  98877. if (maxDepth === void 0) { maxDepth = 2; }
  98878. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98879. if (!component) {
  98880. component = new OctreeSceneComponent(this);
  98881. this._addComponent(component);
  98882. }
  98883. if (!this._selectionOctree) {
  98884. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  98885. }
  98886. var worldExtends = this.getWorldExtends();
  98887. // Update octree
  98888. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  98889. return this._selectionOctree;
  98890. };
  98891. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  98892. get: function () {
  98893. return this._selectionOctree;
  98894. },
  98895. enumerable: true,
  98896. configurable: true
  98897. });
  98898. /**
  98899. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  98900. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  98901. * @param maxCapacity defines the maximum size of each block (64 by default)
  98902. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  98903. * @returns the new octree
  98904. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  98905. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  98906. */
  98907. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  98908. if (maxCapacity === void 0) { maxCapacity = 64; }
  98909. if (maxDepth === void 0) { maxDepth = 2; }
  98910. var scene = this.getScene();
  98911. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  98912. if (!component) {
  98913. component = new OctreeSceneComponent(scene);
  98914. scene._addComponent(component);
  98915. }
  98916. if (!this._submeshesOctree) {
  98917. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  98918. }
  98919. this.computeWorldMatrix(true);
  98920. var boundingInfo = this.getBoundingInfo();
  98921. // Update octree
  98922. var bbox = boundingInfo.boundingBox;
  98923. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  98924. return this._submeshesOctree;
  98925. };
  98926. /**
  98927. * Defines the octree scene component responsible to manage any octrees
  98928. * in a given scene.
  98929. */
  98930. var OctreeSceneComponent = /** @class */ (function () {
  98931. /**
  98932. * Creates a new instance of the component for the given scene
  98933. * @param scene Defines the scene to register the component in
  98934. */
  98935. function OctreeSceneComponent(scene) {
  98936. /**
  98937. * The component name helpfull to identify the component in the list of scene components.
  98938. */
  98939. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  98940. /**
  98941. * Indicates if the meshes have been checked to make sure they are isEnabled()
  98942. */
  98943. this.checksIsEnabled = true;
  98944. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  98945. this.scene = scene;
  98946. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  98947. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  98948. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  98949. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  98950. }
  98951. /**
  98952. * Registers the component in a given scene
  98953. */
  98954. OctreeSceneComponent.prototype.register = function () {
  98955. var _this = this;
  98956. this.scene.onMeshRemovedObservable.add(function (mesh) {
  98957. var sceneOctree = _this.scene.selectionOctree;
  98958. if (sceneOctree !== undefined && sceneOctree !== null) {
  98959. var index = sceneOctree.dynamicContent.indexOf(mesh);
  98960. if (index !== -1) {
  98961. sceneOctree.dynamicContent.splice(index, 1);
  98962. }
  98963. }
  98964. });
  98965. this.scene.onMeshImportedObservable.add(function (mesh) {
  98966. var sceneOctree = _this.scene.selectionOctree;
  98967. if (sceneOctree !== undefined && sceneOctree !== null) {
  98968. sceneOctree.addMesh(mesh);
  98969. }
  98970. });
  98971. };
  98972. /**
  98973. * Return the list of active meshes
  98974. * @returns the list of active meshes
  98975. */
  98976. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  98977. if (this.scene._selectionOctree) {
  98978. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  98979. return selection;
  98980. }
  98981. return this.scene._getDefaultMeshCandidates();
  98982. };
  98983. /**
  98984. * Return the list of active sub meshes
  98985. * @param mesh The mesh to get the candidates sub meshes from
  98986. * @returns the list of active sub meshes
  98987. */
  98988. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  98989. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  98990. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  98991. return intersections;
  98992. }
  98993. return this.scene._getDefaultSubMeshCandidates(mesh);
  98994. };
  98995. /**
  98996. * Return the list of sub meshes intersecting with a given local ray
  98997. * @param mesh defines the mesh to find the submesh for
  98998. * @param localRay defines the ray in local space
  98999. * @returns the list of intersecting sub meshes
  99000. */
  99001. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  99002. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  99003. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  99004. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  99005. return intersections;
  99006. }
  99007. return this.scene._getDefaultSubMeshCandidates(mesh);
  99008. };
  99009. /**
  99010. * Return the list of sub meshes colliding with a collider
  99011. * @param mesh defines the mesh to find the submesh for
  99012. * @param collider defines the collider to evaluate the collision against
  99013. * @returns the list of colliding sub meshes
  99014. */
  99015. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  99016. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  99017. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  99018. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  99019. return intersections;
  99020. }
  99021. return this.scene._getDefaultSubMeshCandidates(mesh);
  99022. };
  99023. /**
  99024. * Rebuilds the elements related to this component in case of
  99025. * context lost for instance.
  99026. */
  99027. OctreeSceneComponent.prototype.rebuild = function () {
  99028. // Nothing to do here.
  99029. };
  99030. /**
  99031. * Disposes the component and the associated ressources.
  99032. */
  99033. OctreeSceneComponent.prototype.dispose = function () {
  99034. // Nothing to do here.
  99035. };
  99036. return OctreeSceneComponent;
  99037. }());
  99038. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  99039. })(BABYLON || (BABYLON = {}));
  99040. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  99041. var BABYLON;
  99042. (function (BABYLON) {
  99043. /**
  99044. * Postprocess used to generate anaglyphic rendering
  99045. */
  99046. var AnaglyphPostProcess = /** @class */ (function (_super) {
  99047. __extends(AnaglyphPostProcess, _super);
  99048. /**
  99049. * Creates a new AnaglyphPostProcess
  99050. * @param name defines postprocess name
  99051. * @param options defines creation options or target ratio scale
  99052. * @param rigCameras defines cameras using this postprocess
  99053. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  99054. * @param engine defines hosting engine
  99055. * @param reusable defines if the postprocess will be reused multiple times per frame
  99056. */
  99057. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  99058. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  99059. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99060. _this.onApplyObservable.add(function (effect) {
  99061. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  99062. });
  99063. return _this;
  99064. }
  99065. return AnaglyphPostProcess;
  99066. }(BABYLON.PostProcess));
  99067. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  99068. })(BABYLON || (BABYLON = {}));
  99069. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  99070. var BABYLON;
  99071. (function (BABYLON) {
  99072. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  99073. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99074. });
  99075. /**
  99076. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  99077. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99078. */
  99079. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  99080. __extends(AnaglyphArcRotateCamera, _super);
  99081. /**
  99082. * Creates a new AnaglyphArcRotateCamera
  99083. * @param name defines camera name
  99084. * @param alpha defines alpha angle (in radians)
  99085. * @param beta defines beta angle (in radians)
  99086. * @param radius defines radius
  99087. * @param target defines camera target
  99088. * @param interaxialDistance defines distance between each color axis
  99089. * @param scene defines the hosting scene
  99090. */
  99091. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  99092. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99093. _this.interaxialDistance = interaxialDistance;
  99094. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99095. return _this;
  99096. }
  99097. /**
  99098. * Gets camera class name
  99099. * @returns AnaglyphArcRotateCamera
  99100. */
  99101. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  99102. return "AnaglyphArcRotateCamera";
  99103. };
  99104. return AnaglyphArcRotateCamera;
  99105. }(BABYLON.ArcRotateCamera));
  99106. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  99107. })(BABYLON || (BABYLON = {}));
  99108. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  99109. var BABYLON;
  99110. (function (BABYLON) {
  99111. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  99112. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99113. });
  99114. /**
  99115. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  99116. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99117. */
  99118. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  99119. __extends(AnaglyphFreeCamera, _super);
  99120. /**
  99121. * Creates a new AnaglyphFreeCamera
  99122. * @param name defines camera name
  99123. * @param position defines initial position
  99124. * @param interaxialDistance defines distance between each color axis
  99125. * @param scene defines the hosting scene
  99126. */
  99127. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  99128. var _this = _super.call(this, name, position, scene) || this;
  99129. _this.interaxialDistance = interaxialDistance;
  99130. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99131. return _this;
  99132. }
  99133. /**
  99134. * Gets camera class name
  99135. * @returns AnaglyphFreeCamera
  99136. */
  99137. AnaglyphFreeCamera.prototype.getClassName = function () {
  99138. return "AnaglyphFreeCamera";
  99139. };
  99140. return AnaglyphFreeCamera;
  99141. }(BABYLON.FreeCamera));
  99142. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  99143. })(BABYLON || (BABYLON = {}));
  99144. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  99145. var BABYLON;
  99146. (function (BABYLON) {
  99147. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  99148. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99149. });
  99150. /**
  99151. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  99152. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99153. */
  99154. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  99155. __extends(AnaglyphGamepadCamera, _super);
  99156. /**
  99157. * Creates a new AnaglyphGamepadCamera
  99158. * @param name defines camera name
  99159. * @param position defines initial position
  99160. * @param interaxialDistance defines distance between each color axis
  99161. * @param scene defines the hosting scene
  99162. */
  99163. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  99164. var _this = _super.call(this, name, position, scene) || this;
  99165. _this.interaxialDistance = interaxialDistance;
  99166. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99167. return _this;
  99168. }
  99169. /**
  99170. * Gets camera class name
  99171. * @returns AnaglyphGamepadCamera
  99172. */
  99173. AnaglyphGamepadCamera.prototype.getClassName = function () {
  99174. return "AnaglyphGamepadCamera";
  99175. };
  99176. return AnaglyphGamepadCamera;
  99177. }(BABYLON.GamepadCamera));
  99178. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  99179. })(BABYLON || (BABYLON = {}));
  99180. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  99181. var BABYLON;
  99182. (function (BABYLON) {
  99183. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  99184. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  99185. });
  99186. /**
  99187. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  99188. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  99189. */
  99190. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  99191. __extends(AnaglyphUniversalCamera, _super);
  99192. /**
  99193. * Creates a new AnaglyphUniversalCamera
  99194. * @param name defines camera name
  99195. * @param position defines initial position
  99196. * @param interaxialDistance defines distance between each color axis
  99197. * @param scene defines the hosting scene
  99198. */
  99199. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  99200. var _this = _super.call(this, name, position, scene) || this;
  99201. _this.interaxialDistance = interaxialDistance;
  99202. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  99203. return _this;
  99204. }
  99205. /**
  99206. * Gets camera class name
  99207. * @returns AnaglyphUniversalCamera
  99208. */
  99209. AnaglyphUniversalCamera.prototype.getClassName = function () {
  99210. return "AnaglyphUniversalCamera";
  99211. };
  99212. return AnaglyphUniversalCamera;
  99213. }(BABYLON.UniversalCamera));
  99214. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  99215. })(BABYLON || (BABYLON = {}));
  99216. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  99217. var BABYLON;
  99218. (function (BABYLON) {
  99219. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  99220. __extends(StereoscopicInterlacePostProcess, _super);
  99221. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  99222. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  99223. _this._passedProcess = rigCameras[0]._rigPostProcess;
  99224. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99225. _this.onSizeChangedObservable.add(function () {
  99226. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  99227. });
  99228. _this.onApplyObservable.add(function (effect) {
  99229. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  99230. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  99231. });
  99232. return _this;
  99233. }
  99234. return StereoscopicInterlacePostProcess;
  99235. }(BABYLON.PostProcess));
  99236. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  99237. })(BABYLON || (BABYLON = {}));
  99238. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  99239. var BABYLON;
  99240. (function (BABYLON) {
  99241. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  99242. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99243. });
  99244. /**
  99245. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  99246. * @see http://doc.babylonjs.com/features/cameras
  99247. */
  99248. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  99249. __extends(StereoscopicArcRotateCamera, _super);
  99250. /**
  99251. * Creates a new StereoscopicArcRotateCamera
  99252. * @param name defines camera name
  99253. * @param alpha defines alpha angle (in radians)
  99254. * @param beta defines beta angle (in radians)
  99255. * @param radius defines radius
  99256. * @param target defines camera target
  99257. * @param interaxialDistance defines distance between each color axis
  99258. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99259. * @param scene defines the hosting scene
  99260. */
  99261. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  99262. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99263. _this.interaxialDistance = interaxialDistance;
  99264. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99265. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99266. return _this;
  99267. }
  99268. /**
  99269. * Gets camera class name
  99270. * @returns StereoscopicArcRotateCamera
  99271. */
  99272. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  99273. return "StereoscopicArcRotateCamera";
  99274. };
  99275. return StereoscopicArcRotateCamera;
  99276. }(BABYLON.ArcRotateCamera));
  99277. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  99278. })(BABYLON || (BABYLON = {}));
  99279. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  99280. var BABYLON;
  99281. (function (BABYLON) {
  99282. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99283. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99284. });
  99285. /**
  99286. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  99287. * @see http://doc.babylonjs.com/features/cameras
  99288. */
  99289. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  99290. __extends(StereoscopicFreeCamera, _super);
  99291. /**
  99292. * Creates a new StereoscopicFreeCamera
  99293. * @param name defines camera name
  99294. * @param position defines initial position
  99295. * @param interaxialDistance defines distance between each color axis
  99296. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99297. * @param scene defines the hosting scene
  99298. */
  99299. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99300. var _this = _super.call(this, name, position, scene) || this;
  99301. _this.interaxialDistance = interaxialDistance;
  99302. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99303. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99304. return _this;
  99305. }
  99306. /**
  99307. * Gets camera class name
  99308. * @returns StereoscopicFreeCamera
  99309. */
  99310. StereoscopicFreeCamera.prototype.getClassName = function () {
  99311. return "StereoscopicFreeCamera";
  99312. };
  99313. return StereoscopicFreeCamera;
  99314. }(BABYLON.FreeCamera));
  99315. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  99316. })(BABYLON || (BABYLON = {}));
  99317. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  99318. var BABYLON;
  99319. (function (BABYLON) {
  99320. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  99321. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99322. });
  99323. /**
  99324. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  99325. * @see http://doc.babylonjs.com/features/cameras
  99326. */
  99327. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  99328. __extends(StereoscopicGamepadCamera, _super);
  99329. /**
  99330. * Creates a new StereoscopicGamepadCamera
  99331. * @param name defines camera name
  99332. * @param position defines initial position
  99333. * @param interaxialDistance defines distance between each color axis
  99334. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99335. * @param scene defines the hosting scene
  99336. */
  99337. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99338. var _this = _super.call(this, name, position, scene) || this;
  99339. _this.interaxialDistance = interaxialDistance;
  99340. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99341. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99342. return _this;
  99343. }
  99344. /**
  99345. * Gets camera class name
  99346. * @returns StereoscopicGamepadCamera
  99347. */
  99348. StereoscopicGamepadCamera.prototype.getClassName = function () {
  99349. return "StereoscopicGamepadCamera";
  99350. };
  99351. return StereoscopicGamepadCamera;
  99352. }(BABYLON.GamepadCamera));
  99353. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  99354. })(BABYLON || (BABYLON = {}));
  99355. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  99356. var BABYLON;
  99357. (function (BABYLON) {
  99358. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  99359. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  99360. });
  99361. /**
  99362. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  99363. * @see http://doc.babylonjs.com/features/cameras
  99364. */
  99365. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  99366. __extends(StereoscopicUniversalCamera, _super);
  99367. /**
  99368. * Creates a new StereoscopicUniversalCamera
  99369. * @param name defines camera name
  99370. * @param position defines initial position
  99371. * @param interaxialDistance defines distance between each color axis
  99372. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  99373. * @param scene defines the hosting scene
  99374. */
  99375. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  99376. var _this = _super.call(this, name, position, scene) || this;
  99377. _this.interaxialDistance = interaxialDistance;
  99378. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  99379. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  99380. return _this;
  99381. }
  99382. /**
  99383. * Gets camera class name
  99384. * @returns StereoscopicUniversalCamera
  99385. */
  99386. StereoscopicUniversalCamera.prototype.getClassName = function () {
  99387. return "StereoscopicUniversalCamera";
  99388. };
  99389. return StereoscopicUniversalCamera;
  99390. }(BABYLON.UniversalCamera));
  99391. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  99392. })(BABYLON || (BABYLON = {}));
  99393. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  99394. var BABYLON;
  99395. (function (BABYLON) {
  99396. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  99397. __extends(VRDistortionCorrectionPostProcess, _super);
  99398. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  99399. var _this = _super.call(this, name, "vrDistortionCorrection", [
  99400. 'LensCenter',
  99401. 'Scale',
  99402. 'ScaleIn',
  99403. 'HmdWarpParam'
  99404. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  99405. _this._isRightEye = isRightEye;
  99406. _this._distortionFactors = vrMetrics.distortionK;
  99407. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  99408. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  99409. _this.adaptScaleToCurrentViewport = true;
  99410. _this.onSizeChangedObservable.add(function () {
  99411. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  99412. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  99413. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  99414. });
  99415. _this.onApplyObservable.add(function (effect) {
  99416. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  99417. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  99418. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  99419. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  99420. });
  99421. return _this;
  99422. }
  99423. return VRDistortionCorrectionPostProcess;
  99424. }(BABYLON.PostProcess));
  99425. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  99426. })(BABYLON || (BABYLON = {}));
  99427. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  99428. var BABYLON;
  99429. (function (BABYLON) {
  99430. /**
  99431. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  99432. * Screen rotation is taken into account.
  99433. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99434. */
  99435. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  99436. /**
  99437. * Instantiates a new input
  99438. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99439. */
  99440. function FreeCameraDeviceOrientationInput() {
  99441. var _this = this;
  99442. this._screenOrientationAngle = 0;
  99443. this._screenQuaternion = new BABYLON.Quaternion();
  99444. this._alpha = 0;
  99445. this._beta = 0;
  99446. this._gamma = 0;
  99447. this._orientationChanged = function () {
  99448. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  99449. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  99450. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  99451. };
  99452. this._deviceOrientation = function (evt) {
  99453. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  99454. _this._beta = evt.beta !== null ? evt.beta : 0;
  99455. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  99456. };
  99457. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  99458. this._orientationChanged();
  99459. }
  99460. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  99461. /**
  99462. * Define the camera controlled by the input.
  99463. */
  99464. get: function () {
  99465. return this._camera;
  99466. },
  99467. set: function (camera) {
  99468. this._camera = camera;
  99469. if (this._camera != null && !this._camera.rotationQuaternion) {
  99470. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  99471. }
  99472. },
  99473. enumerable: true,
  99474. configurable: true
  99475. });
  99476. /**
  99477. * Attach the input controls to a specific dom element to get the input from.
  99478. * @param element Defines the element the controls should be listened from
  99479. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99480. */
  99481. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99482. window.addEventListener("orientationchange", this._orientationChanged);
  99483. window.addEventListener("deviceorientation", this._deviceOrientation);
  99484. //In certain cases, the attach control is called AFTER orientation was changed,
  99485. //So this is needed.
  99486. this._orientationChanged();
  99487. };
  99488. /**
  99489. * Detach the current controls from the specified dom element.
  99490. * @param element Defines the element to stop listening the inputs from
  99491. */
  99492. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  99493. window.removeEventListener("orientationchange", this._orientationChanged);
  99494. window.removeEventListener("deviceorientation", this._deviceOrientation);
  99495. };
  99496. /**
  99497. * Update the current camera state depending on the inputs that have been used this frame.
  99498. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99499. */
  99500. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  99501. //if no device orientation provided, don't update the rotation.
  99502. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  99503. if (!this._alpha)
  99504. return;
  99505. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  99506. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  99507. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  99508. //Mirror on XY Plane
  99509. this._camera.rotationQuaternion.z *= -1;
  99510. this._camera.rotationQuaternion.w *= -1;
  99511. };
  99512. /**
  99513. * Gets the class name of the current intput.
  99514. * @returns the class name
  99515. */
  99516. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  99517. return "FreeCameraDeviceOrientationInput";
  99518. };
  99519. /**
  99520. * Get the friendly name associated with the input class.
  99521. * @returns the input friendly name
  99522. */
  99523. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  99524. return "deviceOrientation";
  99525. };
  99526. return FreeCameraDeviceOrientationInput;
  99527. }());
  99528. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  99529. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  99530. })(BABYLON || (BABYLON = {}));
  99531. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  99532. var BABYLON;
  99533. (function (BABYLON) {
  99534. /**
  99535. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  99536. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  99537. */
  99538. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  99539. /**
  99540. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  99541. */
  99542. function ArcRotateCameraVRDeviceOrientationInput() {
  99543. /**
  99544. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  99545. */
  99546. this.alphaCorrection = 1;
  99547. /**
  99548. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  99549. */
  99550. this.betaCorrection = 1;
  99551. /**
  99552. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  99553. */
  99554. this.gammaCorrection = 1;
  99555. this._alpha = 0;
  99556. this._gamma = 0;
  99557. this._dirty = false;
  99558. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  99559. }
  99560. /**
  99561. * Attach the input controls to a specific dom element to get the input from.
  99562. * @param element Defines the element the controls should be listened from
  99563. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  99564. */
  99565. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  99566. this.camera.attachControl(element, noPreventDefault);
  99567. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  99568. };
  99569. /** @hidden */
  99570. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  99571. if (evt.alpha !== null) {
  99572. this._alpha = +evt.alpha | 0;
  99573. }
  99574. if (evt.gamma !== null) {
  99575. this._gamma = +evt.gamma | 0;
  99576. }
  99577. this._dirty = true;
  99578. };
  99579. /**
  99580. * Update the current camera state depending on the inputs that have been used this frame.
  99581. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  99582. */
  99583. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  99584. if (this._dirty) {
  99585. this._dirty = false;
  99586. if (this._gamma < 0) {
  99587. this._gamma = 180 + this._gamma;
  99588. }
  99589. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  99590. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  99591. }
  99592. };
  99593. /**
  99594. * Detach the current controls from the specified dom element.
  99595. * @param element Defines the element to stop listening the inputs from
  99596. */
  99597. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  99598. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  99599. };
  99600. /**
  99601. * Gets the class name of the current intput.
  99602. * @returns the class name
  99603. */
  99604. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  99605. return "ArcRotateCameraVRDeviceOrientationInput";
  99606. };
  99607. /**
  99608. * Get the friendly name associated with the input class.
  99609. * @returns the input friendly name
  99610. */
  99611. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  99612. return "VRDeviceOrientation";
  99613. };
  99614. return ArcRotateCameraVRDeviceOrientationInput;
  99615. }());
  99616. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  99617. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  99618. })(BABYLON || (BABYLON = {}));
  99619. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  99620. var BABYLON;
  99621. (function (BABYLON) {
  99622. /**
  99623. * This represents all the required metrics to create a VR camera.
  99624. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  99625. */
  99626. var VRCameraMetrics = /** @class */ (function () {
  99627. function VRCameraMetrics() {
  99628. /**
  99629. * Define if the current vr camera should compensate the distortion of the lense or not.
  99630. */
  99631. this.compensateDistortion = true;
  99632. }
  99633. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  99634. /**
  99635. * Gets the rendering aspect ratio based on the provided resolutions.
  99636. */
  99637. get: function () {
  99638. return this.hResolution / (2 * this.vResolution);
  99639. },
  99640. enumerable: true,
  99641. configurable: true
  99642. });
  99643. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  99644. /**
  99645. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  99646. */
  99647. get: function () {
  99648. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  99649. },
  99650. enumerable: true,
  99651. configurable: true
  99652. });
  99653. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  99654. /**
  99655. * @hidden
  99656. */
  99657. get: function () {
  99658. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99659. var h = (4 * meters) / this.hScreenSize;
  99660. return BABYLON.Matrix.Translation(h, 0, 0);
  99661. },
  99662. enumerable: true,
  99663. configurable: true
  99664. });
  99665. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  99666. /**
  99667. * @hidden
  99668. */
  99669. get: function () {
  99670. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  99671. var h = (4 * meters) / this.hScreenSize;
  99672. return BABYLON.Matrix.Translation(-h, 0, 0);
  99673. },
  99674. enumerable: true,
  99675. configurable: true
  99676. });
  99677. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  99678. /**
  99679. * @hidden
  99680. */
  99681. get: function () {
  99682. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  99683. },
  99684. enumerable: true,
  99685. configurable: true
  99686. });
  99687. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  99688. /**
  99689. * @hidden
  99690. */
  99691. get: function () {
  99692. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  99693. },
  99694. enumerable: true,
  99695. configurable: true
  99696. });
  99697. /**
  99698. * Get the default VRMetrics based on the most generic setup.
  99699. * @returns the default vr metrics
  99700. */
  99701. VRCameraMetrics.GetDefault = function () {
  99702. var result = new VRCameraMetrics();
  99703. result.hResolution = 1280;
  99704. result.vResolution = 800;
  99705. result.hScreenSize = 0.149759993;
  99706. result.vScreenSize = 0.0935999975;
  99707. result.vScreenCenter = 0.0467999987;
  99708. result.eyeToScreenDistance = 0.0410000011;
  99709. result.lensSeparationDistance = 0.0635000020;
  99710. result.interpupillaryDistance = 0.0640000030;
  99711. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  99712. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  99713. result.postProcessScaleFactor = 1.714605507808412;
  99714. result.lensCenterOffset = 0.151976421;
  99715. return result;
  99716. };
  99717. return VRCameraMetrics;
  99718. }());
  99719. BABYLON.VRCameraMetrics = VRCameraMetrics;
  99720. })(BABYLON || (BABYLON = {}));
  99721. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  99722. var BABYLON;
  99723. (function (BABYLON) {
  99724. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  99725. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99726. });
  99727. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  99728. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99729. });
  99730. /**
  99731. * This represents a WebVR camera.
  99732. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  99733. * @example http://doc.babylonjs.com/how_to/webvr_camera
  99734. */
  99735. var WebVRFreeCamera = /** @class */ (function (_super) {
  99736. __extends(WebVRFreeCamera, _super);
  99737. /**
  99738. * Instantiates a WebVRFreeCamera.
  99739. * @param name The name of the WebVRFreeCamera
  99740. * @param position The starting anchor position for the camera
  99741. * @param scene The scene the camera belongs to
  99742. * @param webVROptions a set of customizable options for the webVRCamera
  99743. */
  99744. function WebVRFreeCamera(name, position, scene, webVROptions) {
  99745. if (webVROptions === void 0) { webVROptions = {}; }
  99746. var _this = _super.call(this, name, position, scene) || this;
  99747. _this.webVROptions = webVROptions;
  99748. /**
  99749. * @hidden
  99750. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  99751. */
  99752. _this._vrDevice = null;
  99753. /**
  99754. * The rawPose of the vrDevice.
  99755. */
  99756. _this.rawPose = null;
  99757. _this._specsVersion = "1.1";
  99758. _this._attached = false;
  99759. _this._descendants = [];
  99760. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  99761. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  99762. /** @hidden */
  99763. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  99764. _this._standingMatrix = null;
  99765. /**
  99766. * Represents device position in babylon space.
  99767. */
  99768. _this.devicePosition = BABYLON.Vector3.Zero();
  99769. /**
  99770. * Represents device rotation in babylon space.
  99771. */
  99772. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  99773. /**
  99774. * The scale of the device to be used when translating from device space to babylon space.
  99775. */
  99776. _this.deviceScaleFactor = 1;
  99777. _this._deviceToWorld = BABYLON.Matrix.Identity();
  99778. _this._worldToDevice = BABYLON.Matrix.Identity();
  99779. /**
  99780. * References to the webVR controllers for the vrDevice.
  99781. */
  99782. _this.controllers = [];
  99783. /**
  99784. * Emits an event when a controller is attached.
  99785. */
  99786. _this.onControllersAttachedObservable = new BABYLON.Observable();
  99787. /**
  99788. * Emits an event when a controller's mesh has been loaded;
  99789. */
  99790. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99791. /**
  99792. * Emits an event when the HMD's pose has been updated.
  99793. */
  99794. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  99795. _this._poseSet = false;
  99796. /**
  99797. * If the rig cameras be used as parent instead of this camera.
  99798. */
  99799. _this.rigParenting = true;
  99800. _this._defaultHeight = undefined;
  99801. _this._htmlElementAttached = null;
  99802. _this._detachIfAttached = function () {
  99803. var vrDisplay = _this.getEngine().getVRDevice();
  99804. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  99805. _this.detachControl(_this._htmlElementAttached);
  99806. }
  99807. };
  99808. _this._workingVector = BABYLON.Vector3.Zero();
  99809. _this._oneVector = BABYLON.Vector3.One();
  99810. _this._workingMatrix = BABYLON.Matrix.Identity();
  99811. _this._tmpMatrix = new BABYLON.Matrix();
  99812. _this._cache.position = BABYLON.Vector3.Zero();
  99813. if (webVROptions.defaultHeight) {
  99814. _this._defaultHeight = webVROptions.defaultHeight;
  99815. _this.position.y = _this._defaultHeight;
  99816. }
  99817. _this.minZ = 0.1;
  99818. //legacy support - the compensation boolean was removed.
  99819. if (arguments.length === 5) {
  99820. _this.webVROptions = arguments[4];
  99821. }
  99822. // default webVR options
  99823. if (_this.webVROptions.trackPosition == undefined) {
  99824. _this.webVROptions.trackPosition = true;
  99825. }
  99826. if (_this.webVROptions.controllerMeshes == undefined) {
  99827. _this.webVROptions.controllerMeshes = true;
  99828. }
  99829. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  99830. _this.webVROptions.defaultLightingOnControllers = true;
  99831. }
  99832. _this.rotationQuaternion = new BABYLON.Quaternion();
  99833. if (_this.webVROptions && _this.webVROptions.positionScale) {
  99834. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  99835. }
  99836. //enable VR
  99837. var engine = _this.getEngine();
  99838. _this._onVREnabled = function (success) { if (success) {
  99839. _this.initControllers();
  99840. } };
  99841. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  99842. engine.initWebVR().add(function (event) {
  99843. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  99844. return;
  99845. }
  99846. _this._vrDevice = event.vrDisplay;
  99847. //reset the rig parameters.
  99848. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  99849. if (_this._attached) {
  99850. _this.getEngine().enableVR();
  99851. }
  99852. });
  99853. if (typeof (VRFrameData) !== "undefined")
  99854. _this._frameData = new VRFrameData();
  99855. /**
  99856. * The idea behind the following lines:
  99857. * objects that have the camera as parent should actually have the rig cameras as a parent.
  99858. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  99859. * the second will not show it correctly.
  99860. *
  99861. * To solve this - each object that has the camera as parent will be added to a protected array.
  99862. * When the rig camera renders, it will take this array and set all of those to be its children.
  99863. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  99864. * Amazing!
  99865. */
  99866. scene.onBeforeCameraRenderObservable.add(function (camera) {
  99867. if (camera.parent === _this && _this.rigParenting) {
  99868. _this._descendants = _this.getDescendants(true, function (n) {
  99869. // don't take the cameras or the controllers!
  99870. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  99871. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  99872. return !isController && !isRigCamera;
  99873. });
  99874. _this._descendants.forEach(function (node) {
  99875. node.parent = camera;
  99876. });
  99877. }
  99878. });
  99879. scene.onAfterCameraRenderObservable.add(function (camera) {
  99880. if (camera.parent === _this && _this.rigParenting) {
  99881. _this._descendants.forEach(function (node) {
  99882. node.parent = _this;
  99883. });
  99884. }
  99885. });
  99886. return _this;
  99887. }
  99888. /**
  99889. * Gets the device distance from the ground in meters.
  99890. * @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.
  99891. */
  99892. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  99893. if (this._standingMatrix) {
  99894. // Add standing matrix offset to get real offset from ground in room
  99895. this._standingMatrix.getTranslationToRef(this._workingVector);
  99896. return this._deviceRoomPosition.y + this._workingVector.y;
  99897. }
  99898. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  99899. return this._defaultHeight || 0;
  99900. };
  99901. /**
  99902. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99903. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  99904. */
  99905. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  99906. var _this = this;
  99907. if (callback === void 0) { callback = function (bool) { }; }
  99908. // Use standing matrix if available
  99909. this.getEngine().initWebVRAsync().then(function (result) {
  99910. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  99911. callback(false);
  99912. }
  99913. else {
  99914. _this._standingMatrix = new BABYLON.Matrix();
  99915. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  99916. if (!_this.getScene().useRightHandedSystem) {
  99917. [2, 6, 8, 9, 14].forEach(function (num) {
  99918. if (_this._standingMatrix) {
  99919. _this._standingMatrix.m[num] *= -1;
  99920. }
  99921. });
  99922. }
  99923. callback(true);
  99924. }
  99925. });
  99926. };
  99927. /**
  99928. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  99929. * @returns A promise with a boolean set to if the standing matrix is supported.
  99930. */
  99931. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  99932. var _this = this;
  99933. return new Promise(function (res, rej) {
  99934. _this.useStandingMatrix(function (supported) {
  99935. res(supported);
  99936. });
  99937. });
  99938. };
  99939. /**
  99940. * Disposes the camera
  99941. */
  99942. WebVRFreeCamera.prototype.dispose = function () {
  99943. this._detachIfAttached();
  99944. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  99945. if (this._updateCacheWhenTrackingDisabledObserver) {
  99946. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  99947. }
  99948. _super.prototype.dispose.call(this);
  99949. };
  99950. /**
  99951. * Gets a vrController by name.
  99952. * @param name The name of the controller to retreive
  99953. * @returns the controller matching the name specified or null if not found
  99954. */
  99955. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  99956. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  99957. var gp = _a[_i];
  99958. if (gp.hand === name) {
  99959. return gp;
  99960. }
  99961. }
  99962. return null;
  99963. };
  99964. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  99965. /**
  99966. * The controller corrisponding to the users left hand.
  99967. */
  99968. get: function () {
  99969. if (!this._leftController) {
  99970. this._leftController = this.getControllerByName("left");
  99971. }
  99972. return this._leftController;
  99973. },
  99974. enumerable: true,
  99975. configurable: true
  99976. });
  99977. ;
  99978. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  99979. /**
  99980. * The controller corrisponding to the users right hand.
  99981. */
  99982. get: function () {
  99983. if (!this._rightController) {
  99984. this._rightController = this.getControllerByName("right");
  99985. }
  99986. return this._rightController;
  99987. },
  99988. enumerable: true,
  99989. configurable: true
  99990. });
  99991. ;
  99992. /**
  99993. * Casts a ray forward from the vrCamera's gaze.
  99994. * @param length Length of the ray (default: 100)
  99995. * @returns the ray corrisponding to the gaze
  99996. */
  99997. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  99998. if (length === void 0) { length = 100; }
  99999. if (this.leftCamera) {
  100000. // Use left eye to avoid computation to compute center on every call
  100001. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  100002. }
  100003. else {
  100004. return _super.prototype.getForwardRay.call(this, length);
  100005. }
  100006. };
  100007. /**
  100008. * @hidden
  100009. * Updates the camera based on device's frame data
  100010. */
  100011. WebVRFreeCamera.prototype._checkInputs = function () {
  100012. if (this._vrDevice && this._vrDevice.isPresenting) {
  100013. this._vrDevice.getFrameData(this._frameData);
  100014. this.updateFromDevice(this._frameData.pose);
  100015. }
  100016. _super.prototype._checkInputs.call(this);
  100017. };
  100018. /**
  100019. * Updates the poseControlled values based on the input device pose.
  100020. * @param poseData Pose coming from the device
  100021. */
  100022. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  100023. if (poseData && poseData.orientation) {
  100024. this.rawPose = poseData;
  100025. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  100026. if (this.getScene().useRightHandedSystem) {
  100027. this._deviceRoomRotationQuaternion.z *= -1;
  100028. this._deviceRoomRotationQuaternion.w *= -1;
  100029. }
  100030. if (this.webVROptions.trackPosition && this.rawPose.position) {
  100031. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  100032. if (this.getScene().useRightHandedSystem) {
  100033. this._deviceRoomPosition.z *= -1;
  100034. }
  100035. }
  100036. this._poseSet = true;
  100037. }
  100038. };
  100039. /**
  100040. * WebVR's attach control will start broadcasting frames to the device.
  100041. * Note that in certain browsers (chrome for example) this function must be called
  100042. * within a user-interaction callback. Example:
  100043. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  100044. *
  100045. * @param element html element to attach the vrDevice to
  100046. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  100047. */
  100048. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  100049. _super.prototype.attachControl.call(this, element, noPreventDefault);
  100050. this._attached = true;
  100051. this._htmlElementAttached = element;
  100052. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  100053. if (this._vrDevice) {
  100054. this.getEngine().enableVR();
  100055. }
  100056. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100057. };
  100058. /**
  100059. * Detaches the camera from the html element and disables VR
  100060. *
  100061. * @param element html element to detach from
  100062. */
  100063. WebVRFreeCamera.prototype.detachControl = function (element) {
  100064. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  100065. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  100066. _super.prototype.detachControl.call(this, element);
  100067. this._attached = false;
  100068. this.getEngine().disableVR();
  100069. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  100070. };
  100071. /**
  100072. * @returns the name of this class
  100073. */
  100074. WebVRFreeCamera.prototype.getClassName = function () {
  100075. return "WebVRFreeCamera";
  100076. };
  100077. /**
  100078. * Calls resetPose on the vrDisplay
  100079. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  100080. */
  100081. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  100082. //uses the vrDisplay's "resetPose()".
  100083. //pitch and roll won't be affected.
  100084. this._vrDevice.resetPose();
  100085. };
  100086. /**
  100087. * @hidden
  100088. * Updates the rig cameras (left and right eye)
  100089. */
  100090. WebVRFreeCamera.prototype._updateRigCameras = function () {
  100091. var camLeft = this._rigCameras[0];
  100092. var camRight = this._rigCameras[1];
  100093. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100094. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  100095. camLeft.position.copyFrom(this._deviceRoomPosition);
  100096. camRight.position.copyFrom(this._deviceRoomPosition);
  100097. };
  100098. // Remove translation from 6dof headset if trackposition is set to false
  100099. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  100100. if (isViewMatrix === void 0) { isViewMatrix = false; }
  100101. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  100102. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  100103. if (!isViewMatrix) {
  100104. this._tmpMatrix.invert();
  100105. }
  100106. this._tmpMatrix.multiplyToRef(matrix, matrix);
  100107. }
  100108. };
  100109. /**
  100110. * @hidden
  100111. * Updates the cached values of the camera
  100112. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  100113. */
  100114. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  100115. var _this = this;
  100116. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  100117. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  100118. if (!this.updateCacheCalled) {
  100119. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  100120. this.updateCacheCalled = true;
  100121. this.update();
  100122. }
  100123. // Set working vector to the device position in room space rotated by the new rotation
  100124. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  100125. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  100126. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  100127. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  100128. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  100129. // Add translation from anchor position
  100130. this._deviceToWorld.getTranslationToRef(this._workingVector);
  100131. this._workingVector.addInPlace(this.position);
  100132. this._workingVector.subtractInPlace(this._cache.position);
  100133. this._deviceToWorld.setTranslation(this._workingVector);
  100134. // Set an inverted matrix to be used when updating the camera
  100135. this._deviceToWorld.invertToRef(this._worldToDevice);
  100136. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  100137. this.controllers.forEach(function (controller) {
  100138. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  100139. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  100140. controller.update();
  100141. });
  100142. }
  100143. if (!ignoreParentClass) {
  100144. _super.prototype._updateCache.call(this);
  100145. }
  100146. this.updateCacheCalled = false;
  100147. };
  100148. /**
  100149. * @hidden
  100150. * Get current device position in babylon world
  100151. */
  100152. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  100153. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  100154. };
  100155. /**
  100156. * Updates the current device position and rotation in the babylon world
  100157. */
  100158. WebVRFreeCamera.prototype.update = function () {
  100159. this._computeDevicePosition();
  100160. // Get current device rotation in babylon world
  100161. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  100162. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  100163. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  100164. if (this._poseSet) {
  100165. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  100166. }
  100167. _super.prototype.update.call(this);
  100168. };
  100169. /**
  100170. * @hidden
  100171. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  100172. * @returns an identity matrix
  100173. */
  100174. WebVRFreeCamera.prototype._getViewMatrix = function () {
  100175. return BABYLON.Matrix.Identity();
  100176. };
  100177. /**
  100178. * This function is called by the two RIG cameras.
  100179. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  100180. */
  100181. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  100182. var _this = this;
  100183. // Update the parent camera prior to using a child camera to avoid desynchronization
  100184. var parentCamera = this._cameraRigParams["parentCamera"];
  100185. parentCamera._updateCache();
  100186. //WebVR 1.1
  100187. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  100188. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  100189. if (!this.getScene().useRightHandedSystem) {
  100190. [2, 6, 8, 9, 14].forEach(function (num) {
  100191. _this._webvrViewMatrix.m[num] *= -1;
  100192. });
  100193. }
  100194. // update the camera rotation matrix
  100195. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  100196. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  100197. // Computing target and final matrix
  100198. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  100199. // should the view matrix be updated with scale and position offset?
  100200. if (parentCamera.deviceScaleFactor !== 1) {
  100201. this._webvrViewMatrix.invert();
  100202. // scale the position, if set
  100203. if (parentCamera.deviceScaleFactor) {
  100204. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  100205. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  100206. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  100207. }
  100208. this._webvrViewMatrix.invert();
  100209. }
  100210. // Remove translation from 6dof headset if trackposition is set to false
  100211. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  100212. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  100213. // Compute global position
  100214. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  100215. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  100216. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  100217. this._workingMatrix.getTranslationToRef(this._globalPosition);
  100218. this._markSyncedWithParent();
  100219. return this._webvrViewMatrix;
  100220. };
  100221. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  100222. var _this = this;
  100223. var parentCamera = this.parent;
  100224. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  100225. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  100226. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  100227. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  100228. //babylon compatible matrix
  100229. if (!this.getScene().useRightHandedSystem) {
  100230. [8, 9, 10, 11].forEach(function (num) {
  100231. _this._projectionMatrix.m[num] *= -1;
  100232. });
  100233. }
  100234. return this._projectionMatrix;
  100235. };
  100236. /**
  100237. * Initializes the controllers and their meshes
  100238. */
  100239. WebVRFreeCamera.prototype.initControllers = function () {
  100240. var _this = this;
  100241. this.controllers = [];
  100242. var manager = this.getScene().gamepadManager;
  100243. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  100244. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100245. var webVrController = gamepad;
  100246. if (webVrController.defaultModel) {
  100247. webVrController.defaultModel.setEnabled(false);
  100248. }
  100249. if (webVrController.hand === "right") {
  100250. _this._rightController = null;
  100251. }
  100252. if (webVrController.hand === "left") {
  100253. _this._leftController = null;
  100254. }
  100255. var controllerIndex = _this.controllers.indexOf(webVrController);
  100256. if (controllerIndex !== -1) {
  100257. _this.controllers.splice(controllerIndex, 1);
  100258. }
  100259. }
  100260. });
  100261. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  100262. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  100263. var webVrController_1 = gamepad;
  100264. if (!_this.webVROptions.trackPosition) {
  100265. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  100266. // Cache must be updated before rendering controllers to avoid them being one frame behind
  100267. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  100268. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  100269. _this._updateCache();
  100270. });
  100271. }
  100272. }
  100273. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  100274. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  100275. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  100276. if (_this.webVROptions.controllerMeshes) {
  100277. if (webVrController_1.defaultModel) {
  100278. webVrController_1.defaultModel.setEnabled(true);
  100279. }
  100280. else {
  100281. // Load the meshes
  100282. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  100283. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  100284. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  100285. if (_this.webVROptions.defaultLightingOnControllers) {
  100286. if (!_this._lightOnControllers) {
  100287. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  100288. }
  100289. var activateLightOnSubMeshes_1 = function (mesh, light) {
  100290. var children = mesh.getChildren();
  100291. if (children && children.length !== 0) {
  100292. children.forEach(function (mesh) {
  100293. light.includedOnlyMeshes.push(mesh);
  100294. activateLightOnSubMeshes_1(mesh, light);
  100295. });
  100296. }
  100297. };
  100298. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  100299. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  100300. }
  100301. });
  100302. }
  100303. }
  100304. webVrController_1.attachToPoseControlledCamera(_this);
  100305. // since this is async - sanity check. Is the controller already stored?
  100306. if (_this.controllers.indexOf(webVrController_1) === -1) {
  100307. //add to the controllers array
  100308. _this.controllers.push(webVrController_1);
  100309. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  100310. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  100311. // So we're overriding setting left & right manually to be sure
  100312. var firstViveWandDetected = false;
  100313. for (var i = 0; i < _this.controllers.length; i++) {
  100314. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100315. if (!firstViveWandDetected) {
  100316. firstViveWandDetected = true;
  100317. _this.controllers[i].hand = "left";
  100318. }
  100319. else {
  100320. _this.controllers[i].hand = "right";
  100321. }
  100322. }
  100323. }
  100324. //did we find enough controllers? Great! let the developer know.
  100325. if (_this.controllers.length >= 2) {
  100326. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  100327. }
  100328. }
  100329. }
  100330. });
  100331. };
  100332. return WebVRFreeCamera;
  100333. }(BABYLON.FreeCamera));
  100334. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  100335. })(BABYLON || (BABYLON = {}));
  100336. //# sourceMappingURL=babylon.webVRCamera.js.map
  100337. var BABYLON;
  100338. (function (BABYLON) {
  100339. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  100340. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  100341. });
  100342. // We're mainly based on the logic defined into the FreeCamera code
  100343. /**
  100344. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  100345. * being tilted forward or back and left or right.
  100346. */
  100347. var DeviceOrientationCamera = /** @class */ (function (_super) {
  100348. __extends(DeviceOrientationCamera, _super);
  100349. /**
  100350. * Creates a new device orientation camera
  100351. * @param name The name of the camera
  100352. * @param position The start position camera
  100353. * @param scene The scene the camera belongs to
  100354. */
  100355. function DeviceOrientationCamera(name, position, scene) {
  100356. var _this = _super.call(this, name, position, scene) || this;
  100357. _this._quaternionCache = new BABYLON.Quaternion();
  100358. _this.inputs.addDeviceOrientation();
  100359. return _this;
  100360. }
  100361. /**
  100362. * Gets the current instance class name ("DeviceOrientationCamera").
  100363. * This helps avoiding instanceof at run time.
  100364. * @returns the class name
  100365. */
  100366. DeviceOrientationCamera.prototype.getClassName = function () {
  100367. return "DeviceOrientationCamera";
  100368. };
  100369. /**
  100370. * @hidden
  100371. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  100372. */
  100373. DeviceOrientationCamera.prototype._checkInputs = function () {
  100374. _super.prototype._checkInputs.call(this);
  100375. this._quaternionCache.copyFrom(this.rotationQuaternion);
  100376. if (this._initialQuaternion) {
  100377. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100378. }
  100379. };
  100380. /**
  100381. * Reset the camera to its default orientation on the specified axis only.
  100382. * @param axis The axis to reset
  100383. */
  100384. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  100385. var _this = this;
  100386. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  100387. //can only work if this camera has a rotation quaternion already.
  100388. if (!this.rotationQuaternion)
  100389. return;
  100390. if (!this._initialQuaternion) {
  100391. this._initialQuaternion = new BABYLON.Quaternion();
  100392. }
  100393. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  100394. ['x', 'y', 'z'].forEach(function (axisName) {
  100395. if (!axis[axisName]) {
  100396. _this._initialQuaternion[axisName] = 0;
  100397. }
  100398. else {
  100399. _this._initialQuaternion[axisName] *= -1;
  100400. }
  100401. });
  100402. this._initialQuaternion.normalize();
  100403. //force rotation update
  100404. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  100405. };
  100406. return DeviceOrientationCamera;
  100407. }(BABYLON.FreeCamera));
  100408. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  100409. })(BABYLON || (BABYLON = {}));
  100410. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  100411. var BABYLON;
  100412. (function (BABYLON) {
  100413. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100414. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  100415. });
  100416. /**
  100417. * Camera used to simulate VR rendering (based on FreeCamera)
  100418. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100419. */
  100420. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  100421. __extends(VRDeviceOrientationFreeCamera, _super);
  100422. /**
  100423. * Creates a new VRDeviceOrientationFreeCamera
  100424. * @param name defines camera name
  100425. * @param position defines the start position of the camera
  100426. * @param scene defines the scene the camera belongs to
  100427. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100428. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100429. */
  100430. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100431. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100432. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100433. var _this = _super.call(this, name, position, scene) || this;
  100434. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100435. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100436. return _this;
  100437. }
  100438. /**
  100439. * Gets camera class name
  100440. * @returns VRDeviceOrientationFreeCamera
  100441. */
  100442. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  100443. return "VRDeviceOrientationFreeCamera";
  100444. };
  100445. return VRDeviceOrientationFreeCamera;
  100446. }(BABYLON.DeviceOrientationCamera));
  100447. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  100448. })(BABYLON || (BABYLON = {}));
  100449. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  100450. var BABYLON;
  100451. (function (BABYLON) {
  100452. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  100453. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  100454. });
  100455. /**
  100456. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  100457. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100458. */
  100459. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  100460. __extends(VRDeviceOrientationArcRotateCamera, _super);
  100461. /**
  100462. * Creates a new VRDeviceOrientationArcRotateCamera
  100463. * @param name defines camera name
  100464. * @param alpha defines the camera rotation along the logitudinal axis
  100465. * @param beta defines the camera rotation along the latitudinal axis
  100466. * @param radius defines the camera distance from its target
  100467. * @param target defines the camera target
  100468. * @param scene defines the scene the camera belongs to
  100469. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100470. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100471. */
  100472. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  100473. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100474. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100475. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  100476. vrCameraMetrics.compensateDistortion = compensateDistortion;
  100477. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  100478. _this.inputs.addVRDeviceOrientation();
  100479. return _this;
  100480. }
  100481. /**
  100482. * Gets camera class name
  100483. * @returns VRDeviceOrientationArcRotateCamera
  100484. */
  100485. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  100486. return "VRDeviceOrientationArcRotateCamera";
  100487. };
  100488. return VRDeviceOrientationArcRotateCamera;
  100489. }(BABYLON.ArcRotateCamera));
  100490. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  100491. })(BABYLON || (BABYLON = {}));
  100492. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  100493. var BABYLON;
  100494. (function (BABYLON) {
  100495. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  100496. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  100497. });
  100498. /**
  100499. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  100500. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  100501. */
  100502. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  100503. __extends(VRDeviceOrientationGamepadCamera, _super);
  100504. /**
  100505. * Creates a new VRDeviceOrientationGamepadCamera
  100506. * @param name defines camera name
  100507. * @param position defines the start position of the camera
  100508. * @param scene defines the scene the camera belongs to
  100509. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  100510. * @param vrCameraMetrics defines the vr metrics associated to the camera
  100511. */
  100512. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  100513. if (compensateDistortion === void 0) { compensateDistortion = true; }
  100514. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  100515. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  100516. _this.inputs.addGamepad();
  100517. return _this;
  100518. }
  100519. /**
  100520. * Gets camera class name
  100521. * @returns VRDeviceOrientationGamepadCamera
  100522. */
  100523. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  100524. return "VRDeviceOrientationGamepadCamera";
  100525. };
  100526. return VRDeviceOrientationGamepadCamera;
  100527. }(BABYLON.VRDeviceOrientationFreeCamera));
  100528. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  100529. })(BABYLON || (BABYLON = {}));
  100530. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  100531. var BABYLON;
  100532. (function (BABYLON) {
  100533. var VRExperienceHelperGazer = /** @class */ (function () {
  100534. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  100535. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  100536. this.scene = scene;
  100537. /** @hidden */
  100538. this._pointerDownOnMeshAsked = false;
  100539. /** @hidden */
  100540. this._isActionableMesh = false;
  100541. /** @hidden */
  100542. this._teleportationRequestInitiated = false;
  100543. /** @hidden */
  100544. this._teleportationBackRequestInitiated = false;
  100545. /** @hidden */
  100546. this._rotationRightAsked = false;
  100547. /** @hidden */
  100548. this._rotationLeftAsked = false;
  100549. /** @hidden */
  100550. this._dpadPressed = true;
  100551. /** @hidden */
  100552. this._activePointer = false;
  100553. this._id = VRExperienceHelperGazer._idCounter++;
  100554. // Gaze tracker
  100555. if (!gazeTrackerToClone) {
  100556. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  100557. this._gazeTracker.bakeCurrentTransformIntoVertices();
  100558. this._gazeTracker.isPickable = false;
  100559. this._gazeTracker.isVisible = false;
  100560. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  100561. targetMat.specularColor = BABYLON.Color3.Black();
  100562. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100563. targetMat.backFaceCulling = false;
  100564. this._gazeTracker.material = targetMat;
  100565. }
  100566. else {
  100567. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  100568. }
  100569. }
  100570. /** @hidden */
  100571. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  100572. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  100573. };
  100574. /** @hidden */
  100575. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  100576. this._pointerDownOnMeshAsked = true;
  100577. if (this._currentHit) {
  100578. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  100579. }
  100580. };
  100581. /** @hidden */
  100582. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  100583. if (this._currentHit) {
  100584. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  100585. }
  100586. this._pointerDownOnMeshAsked = false;
  100587. };
  100588. /** @hidden */
  100589. VRExperienceHelperGazer.prototype._activatePointer = function () {
  100590. this._activePointer = true;
  100591. };
  100592. /** @hidden */
  100593. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  100594. this._activePointer = false;
  100595. };
  100596. /** @hidden */
  100597. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  100598. if (distance === void 0) { distance = 100; }
  100599. };
  100600. VRExperienceHelperGazer.prototype.dispose = function () {
  100601. this._interactionsEnabled = false;
  100602. this._teleportationEnabled = false;
  100603. if (this._gazeTracker) {
  100604. this._gazeTracker.dispose();
  100605. }
  100606. };
  100607. VRExperienceHelperGazer._idCounter = 0;
  100608. return VRExperienceHelperGazer;
  100609. }());
  100610. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  100611. __extends(VRExperienceHelperControllerGazer, _super);
  100612. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  100613. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  100614. _this.webVRController = webVRController;
  100615. // Laser pointer
  100616. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  100617. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  100618. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  100619. laserPointerMaterial.alpha = 0.6;
  100620. _this._laserPointer.material = laserPointerMaterial;
  100621. _this._laserPointer.rotation.x = Math.PI / 2;
  100622. _this._laserPointer.position.z = -0.5;
  100623. _this._laserPointer.isVisible = false;
  100624. _this._laserPointer.isPickable = false;
  100625. if (!webVRController.mesh) {
  100626. // Create an empty mesh that is used prior to loading the high quality model
  100627. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  100628. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  100629. preloadPointerPose.rotation.x = -0.7;
  100630. preloadMesh.addChild(preloadPointerPose);
  100631. webVRController.attachToMesh(preloadMesh);
  100632. }
  100633. _this._setLaserPointerParent(webVRController.mesh);
  100634. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  100635. _this._setLaserPointerParent(mesh);
  100636. });
  100637. return _this;
  100638. }
  100639. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  100640. return this.webVRController.getForwardRay(length);
  100641. };
  100642. /** @hidden */
  100643. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  100644. _super.prototype._activatePointer.call(this);
  100645. this._laserPointer.isVisible = true;
  100646. };
  100647. /** @hidden */
  100648. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  100649. _super.prototype._deactivatePointer.call(this);
  100650. this._laserPointer.isVisible = false;
  100651. };
  100652. /** @hidden */
  100653. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  100654. this._laserPointer.material.emissiveColor = color;
  100655. };
  100656. /** @hidden */
  100657. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  100658. var makeNotPick = function (root) {
  100659. root.isPickable = false;
  100660. root.getChildMeshes().forEach(function (c) {
  100661. makeNotPick(c);
  100662. });
  100663. };
  100664. makeNotPick(mesh);
  100665. var childMeshes = mesh.getChildMeshes();
  100666. this.webVRController._pointingPoseNode = null;
  100667. for (var i = 0; i < childMeshes.length; i++) {
  100668. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  100669. mesh = childMeshes[i];
  100670. this.webVRController._pointingPoseNode = mesh;
  100671. break;
  100672. }
  100673. }
  100674. this._laserPointer.parent = mesh;
  100675. };
  100676. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  100677. if (distance === void 0) { distance = 100; }
  100678. this._laserPointer.scaling.y = distance;
  100679. this._laserPointer.position.z = -distance / 2;
  100680. };
  100681. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  100682. _super.prototype.dispose.call(this);
  100683. this._laserPointer.dispose();
  100684. if (this._meshAttachedObserver) {
  100685. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  100686. }
  100687. };
  100688. return VRExperienceHelperControllerGazer;
  100689. }(VRExperienceHelperGazer));
  100690. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  100691. __extends(VRExperienceHelperCameraGazer, _super);
  100692. function VRExperienceHelperCameraGazer(getCamera, scene) {
  100693. var _this = _super.call(this, scene) || this;
  100694. _this.getCamera = getCamera;
  100695. return _this;
  100696. }
  100697. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  100698. var camera = this.getCamera();
  100699. if (camera) {
  100700. return camera.getForwardRay(length);
  100701. }
  100702. else {
  100703. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  100704. }
  100705. };
  100706. return VRExperienceHelperCameraGazer;
  100707. }(VRExperienceHelperGazer));
  100708. /**
  100709. * Helps to quickly add VR support to an existing scene.
  100710. * See http://doc.babylonjs.com/how_to/webvr_helper
  100711. */
  100712. var VRExperienceHelper = /** @class */ (function () {
  100713. /**
  100714. * Instantiates a VRExperienceHelper.
  100715. * Helps to quickly add VR support to an existing scene.
  100716. * @param scene The scene the VRExperienceHelper belongs to.
  100717. * @param webVROptions Options to modify the vr experience helper's behavior.
  100718. */
  100719. function VRExperienceHelper(scene,
  100720. /** Options to modify the vr experience helper's behavior. */
  100721. webVROptions) {
  100722. if (webVROptions === void 0) { webVROptions = {}; }
  100723. var _this = this;
  100724. this.webVROptions = webVROptions;
  100725. // Can the system support WebVR, even if a headset isn't plugged in?
  100726. this._webVRsupported = false;
  100727. // If WebVR is supported, is a headset plugged in and are we ready to present?
  100728. this._webVRready = false;
  100729. // Are we waiting for the requestPresent callback to complete?
  100730. this._webVRrequesting = false;
  100731. // Are we presenting to the headset right now? (this is the vrDevice state)
  100732. this._webVRpresenting = false;
  100733. // Are we presenting in the fullscreen fallback?
  100734. this._fullscreenVRpresenting = false;
  100735. /**
  100736. * Observable raised when entering VR.
  100737. */
  100738. this.onEnteringVRObservable = new BABYLON.Observable();
  100739. /**
  100740. * Observable raised when exiting VR.
  100741. */
  100742. this.onExitingVRObservable = new BABYLON.Observable();
  100743. /**
  100744. * Observable raised when controller mesh is loaded.
  100745. */
  100746. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  100747. this._useCustomVRButton = false;
  100748. this._teleportationRequested = false;
  100749. this._teleportActive = false;
  100750. this._floorMeshesCollection = [];
  100751. this._rotationAllowed = true;
  100752. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  100753. this._isDefaultTeleportationTarget = true;
  100754. this._teleportationFillColor = "#444444";
  100755. this._teleportationBorderColor = "#FFFFFF";
  100756. this._rotationAngle = 0;
  100757. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  100758. this._padSensibilityUp = 0.65;
  100759. this._padSensibilityDown = 0.35;
  100760. this._leftController = null;
  100761. this._rightController = null;
  100762. /**
  100763. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  100764. */
  100765. this.onNewMeshSelected = new BABYLON.Observable();
  100766. /**
  100767. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  100768. */
  100769. this.onNewMeshPicked = new BABYLON.Observable();
  100770. /**
  100771. * Observable raised before camera teleportation
  100772. */
  100773. this.onBeforeCameraTeleport = new BABYLON.Observable();
  100774. /**
  100775. * Observable raised after camera teleportation
  100776. */
  100777. this.onAfterCameraTeleport = new BABYLON.Observable();
  100778. /**
  100779. * Observable raised when current selected mesh gets unselected
  100780. */
  100781. this.onSelectedMeshUnselected = new BABYLON.Observable();
  100782. /**
  100783. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  100784. */
  100785. this.teleportationEnabled = true;
  100786. this._teleportationInitialized = false;
  100787. this._interactionsEnabled = false;
  100788. this._interactionsRequested = false;
  100789. this._displayGaze = true;
  100790. this._displayLaserPointer = true;
  100791. /**
  100792. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  100793. */
  100794. this.updateGazeTrackerScale = true;
  100795. this._onResize = function () {
  100796. _this.moveButtonToBottomRight();
  100797. if (_this._fullscreenVRpresenting && _this._webVRready) {
  100798. _this.exitVR();
  100799. }
  100800. };
  100801. this._onFullscreenChange = function () {
  100802. if (document.fullscreen !== undefined) {
  100803. _this._fullscreenVRpresenting = document.fullscreen;
  100804. }
  100805. else if (document.mozFullScreen !== undefined) {
  100806. _this._fullscreenVRpresenting = document.mozFullScreen;
  100807. }
  100808. else if (document.webkitIsFullScreen !== undefined) {
  100809. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  100810. }
  100811. else if (document.msIsFullScreen !== undefined) {
  100812. _this._fullscreenVRpresenting = document.msIsFullScreen;
  100813. }
  100814. else if (document.msFullscreenElement !== undefined) {
  100815. _this._fullscreenVRpresenting = document.msFullscreenElement;
  100816. }
  100817. if (!_this._fullscreenVRpresenting && _this._canvas) {
  100818. _this.exitVR();
  100819. if (!_this._useCustomVRButton) {
  100820. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  100821. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  100822. }
  100823. }
  100824. };
  100825. this.beforeRender = function () {
  100826. if (_this._leftController && _this._leftController._activePointer) {
  100827. _this._castRayAndSelectObject(_this._leftController);
  100828. }
  100829. if (_this._rightController && _this._rightController._activePointer) {
  100830. _this._castRayAndSelectObject(_this._rightController);
  100831. }
  100832. if (_this._noControllerIsActive) {
  100833. _this._castRayAndSelectObject(_this._cameraGazer);
  100834. }
  100835. else {
  100836. _this._cameraGazer._gazeTracker.isVisible = false;
  100837. }
  100838. };
  100839. this._onNewGamepadConnected = function (gamepad) {
  100840. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  100841. if (gamepad.leftStick) {
  100842. gamepad.onleftstickchanged(function (stickValues) {
  100843. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  100844. // Listening to classic/xbox gamepad only if no VR controller is active
  100845. if ((!_this._leftController && !_this._rightController) ||
  100846. ((_this._leftController && !_this._leftController._activePointer) &&
  100847. (_this._rightController && !_this._rightController._activePointer))) {
  100848. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  100849. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  100850. }
  100851. }
  100852. });
  100853. }
  100854. if (gamepad.rightStick) {
  100855. gamepad.onrightstickchanged(function (stickValues) {
  100856. if (_this._teleportationInitialized) {
  100857. _this._checkRotate(stickValues, _this._cameraGazer);
  100858. }
  100859. });
  100860. }
  100861. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  100862. gamepad.onbuttondown(function (buttonPressed) {
  100863. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100864. _this._cameraGazer._selectionPointerDown();
  100865. }
  100866. });
  100867. gamepad.onbuttonup(function (buttonPressed) {
  100868. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  100869. _this._cameraGazer._selectionPointerUp();
  100870. }
  100871. });
  100872. }
  100873. }
  100874. else {
  100875. var webVRController = gamepad;
  100876. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  100877. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  100878. _this._rightController = controller;
  100879. }
  100880. else {
  100881. _this._leftController = controller;
  100882. }
  100883. _this._tryEnableInteractionOnController(controller);
  100884. }
  100885. };
  100886. // 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
  100887. this._tryEnableInteractionOnController = function (controller) {
  100888. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  100889. _this._enableInteractionOnController(controller);
  100890. }
  100891. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  100892. _this._enableTeleportationOnController(controller);
  100893. }
  100894. };
  100895. this._onNewGamepadDisconnected = function (gamepad) {
  100896. if (gamepad instanceof BABYLON.WebVRController) {
  100897. if (gamepad.hand === "left" && _this._leftController != null) {
  100898. _this._leftController.dispose();
  100899. _this._leftController = null;
  100900. }
  100901. if (gamepad.hand === "right" && _this._rightController != null) {
  100902. _this._rightController.dispose();
  100903. _this._rightController = null;
  100904. }
  100905. }
  100906. };
  100907. this._workingVector = BABYLON.Vector3.Zero();
  100908. this._workingQuaternion = BABYLON.Quaternion.Identity();
  100909. this._workingMatrix = BABYLON.Matrix.Identity();
  100910. this._scene = scene;
  100911. this._canvas = scene.getEngine().getRenderingCanvas();
  100912. // Parse options
  100913. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  100914. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  100915. }
  100916. if (webVROptions.createDeviceOrientationCamera === undefined) {
  100917. webVROptions.createDeviceOrientationCamera = true;
  100918. }
  100919. if (webVROptions.laserToggle === undefined) {
  100920. webVROptions.laserToggle = true;
  100921. }
  100922. if (webVROptions.defaultHeight === undefined) {
  100923. webVROptions.defaultHeight = 1.7;
  100924. }
  100925. if (webVROptions.useCustomVRButton) {
  100926. this._useCustomVRButton = true;
  100927. if (webVROptions.customVRButton) {
  100928. this._btnVR = webVROptions.customVRButton;
  100929. }
  100930. }
  100931. if (webVROptions.rayLength) {
  100932. this._rayLength = webVROptions.rayLength;
  100933. }
  100934. this._defaultHeight = webVROptions.defaultHeight;
  100935. if (webVROptions.positionScale) {
  100936. this._rayLength *= webVROptions.positionScale;
  100937. this._defaultHeight *= webVROptions.positionScale;
  100938. }
  100939. this._hasEnteredVR = false;
  100940. // Set position
  100941. if (this._scene.activeCamera) {
  100942. this._position = this._scene.activeCamera.position.clone();
  100943. }
  100944. else {
  100945. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  100946. }
  100947. // Set non-vr camera
  100948. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  100949. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  100950. // Copy data from existing camera
  100951. if (this._scene.activeCamera) {
  100952. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100953. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  100954. // Set rotation from previous camera
  100955. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  100956. var targetCamera = this._scene.activeCamera;
  100957. if (targetCamera.rotationQuaternion) {
  100958. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  100959. }
  100960. else {
  100961. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  100962. }
  100963. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  100964. }
  100965. }
  100966. this._scene.activeCamera = this._deviceOrientationCamera;
  100967. if (this._canvas) {
  100968. this._scene.activeCamera.attachControl(this._canvas);
  100969. }
  100970. }
  100971. else {
  100972. this._existingCamera = this._scene.activeCamera;
  100973. }
  100974. // Create VR cameras
  100975. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  100976. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  100977. }
  100978. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  100979. this._webVRCamera.useStandingMatrix();
  100980. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  100981. // Create default button
  100982. if (!this._useCustomVRButton) {
  100983. this._btnVR = document.createElement("BUTTON");
  100984. this._btnVR.className = "babylonVRicon";
  100985. this._btnVR.id = "babylonVRiconbtn";
  100986. this._btnVR.title = "Click to switch to VR";
  100987. 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) }";
  100988. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  100989. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  100990. // css += ".babylonVRicon.vrdisplaysupported { }";
  100991. // css += ".babylonVRicon.vrdisplayready { }";
  100992. // css += ".babylonVRicon.vrdisplayrequesting { }";
  100993. var style = document.createElement('style');
  100994. style.appendChild(document.createTextNode(css));
  100995. document.getElementsByTagName('head')[0].appendChild(style);
  100996. this.moveButtonToBottomRight();
  100997. }
  100998. // VR button click event
  100999. if (this._btnVR) {
  101000. this._btnVR.addEventListener("click", function () {
  101001. if (!_this.isInVRMode) {
  101002. _this.enterVR();
  101003. }
  101004. else {
  101005. _this.exitVR();
  101006. }
  101007. });
  101008. }
  101009. // Window events
  101010. window.addEventListener("resize", this._onResize);
  101011. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  101012. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  101013. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  101014. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  101015. document.onmsfullscreenchange = this._onFullscreenChange;
  101016. // Display vr button when headset is connected
  101017. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  101018. this.displayVRButton();
  101019. }
  101020. else {
  101021. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  101022. if (e.vrDisplay) {
  101023. _this.displayVRButton();
  101024. }
  101025. });
  101026. }
  101027. // Exiting VR mode using 'ESC' key on desktop
  101028. this._onKeyDown = function (event) {
  101029. if (event.keyCode === 27 && _this.isInVRMode) {
  101030. _this.exitVR();
  101031. }
  101032. };
  101033. document.addEventListener("keydown", this._onKeyDown);
  101034. // Exiting VR mode double tapping the touch screen
  101035. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  101036. if (_this.isInVRMode) {
  101037. _this.exitVR();
  101038. if (_this._fullscreenVRpresenting) {
  101039. _this._scene.getEngine().switchFullscreen(true);
  101040. }
  101041. }
  101042. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  101043. // Listen for WebVR display changes
  101044. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  101045. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  101046. this._onVRRequestPresentStart = function () {
  101047. _this._webVRrequesting = true;
  101048. _this.updateButtonVisibility();
  101049. };
  101050. this._onVRRequestPresentComplete = function (success) {
  101051. _this._webVRrequesting = false;
  101052. _this.updateButtonVisibility();
  101053. };
  101054. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  101055. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  101056. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  101057. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101058. scene.onDisposeObservable.add(function () {
  101059. _this.dispose();
  101060. });
  101061. // Gamepad connection events
  101062. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  101063. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  101064. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  101065. this.updateButtonVisibility();
  101066. //create easing functions
  101067. this._circleEase = new BABYLON.CircleEase();
  101068. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101069. if (this.webVROptions.floorMeshes) {
  101070. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  101071. }
  101072. }
  101073. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  101074. /** Return this.onEnteringVRObservable
  101075. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  101076. */
  101077. get: function () {
  101078. return this.onEnteringVRObservable;
  101079. },
  101080. enumerable: true,
  101081. configurable: true
  101082. });
  101083. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  101084. /** Return this.onExitingVRObservable
  101085. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  101086. */
  101087. get: function () {
  101088. return this.onExitingVRObservable;
  101089. },
  101090. enumerable: true,
  101091. configurable: true
  101092. });
  101093. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  101094. /** Return this.onControllerMeshLoadedObservable
  101095. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  101096. */
  101097. get: function () {
  101098. return this.onControllerMeshLoadedObservable;
  101099. },
  101100. enumerable: true,
  101101. configurable: true
  101102. });
  101103. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  101104. /**
  101105. * The mesh used to display where the user is going to teleport.
  101106. */
  101107. get: function () {
  101108. return this._teleportationTarget;
  101109. },
  101110. /**
  101111. * Sets the mesh to be used to display where the user is going to teleport.
  101112. */
  101113. set: function (value) {
  101114. if (value) {
  101115. value.name = "teleportationTarget";
  101116. this._isDefaultTeleportationTarget = false;
  101117. this._teleportationTarget = value;
  101118. }
  101119. },
  101120. enumerable: true,
  101121. configurable: true
  101122. });
  101123. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  101124. /**
  101125. * 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
  101126. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  101127. * See http://doc.babylonjs.com/resources/baking_transformations
  101128. */
  101129. get: function () {
  101130. return this._cameraGazer._gazeTracker;
  101131. },
  101132. set: function (value) {
  101133. if (value) {
  101134. // Dispose of existing meshes
  101135. if (this._cameraGazer._gazeTracker) {
  101136. this._cameraGazer._gazeTracker.dispose();
  101137. }
  101138. if (this._leftController && this._leftController._gazeTracker) {
  101139. this._leftController._gazeTracker.dispose();
  101140. }
  101141. if (this._rightController && this._rightController._gazeTracker) {
  101142. this._rightController._gazeTracker.dispose();
  101143. }
  101144. // Set and create gaze trackers on head and controllers
  101145. this._cameraGazer._gazeTracker = value;
  101146. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  101147. this._cameraGazer._gazeTracker.isPickable = false;
  101148. this._cameraGazer._gazeTracker.isVisible = false;
  101149. this._cameraGazer._gazeTracker.name = "gazeTracker";
  101150. if (this._leftController) {
  101151. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101152. }
  101153. if (this._rightController) {
  101154. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  101155. }
  101156. }
  101157. },
  101158. enumerable: true,
  101159. configurable: true
  101160. });
  101161. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  101162. /**
  101163. * The gaze tracking mesh corresponding to the left controller
  101164. */
  101165. get: function () {
  101166. if (this._leftController) {
  101167. return this._leftController._gazeTracker;
  101168. }
  101169. return null;
  101170. },
  101171. enumerable: true,
  101172. configurable: true
  101173. });
  101174. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  101175. /**
  101176. * The gaze tracking mesh corresponding to the right controller
  101177. */
  101178. get: function () {
  101179. if (this._rightController) {
  101180. return this._rightController._gazeTracker;
  101181. }
  101182. return null;
  101183. },
  101184. enumerable: true,
  101185. configurable: true
  101186. });
  101187. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  101188. /**
  101189. * If the ray of the gaze should be displayed.
  101190. */
  101191. get: function () {
  101192. return this._displayGaze;
  101193. },
  101194. /**
  101195. * Sets if the ray of the gaze should be displayed.
  101196. */
  101197. set: function (value) {
  101198. this._displayGaze = value;
  101199. if (!value) {
  101200. this._cameraGazer._gazeTracker.isVisible = false;
  101201. if (this._leftController) {
  101202. this._leftController._gazeTracker.isVisible = false;
  101203. }
  101204. if (this._rightController) {
  101205. this._rightController._gazeTracker.isVisible = false;
  101206. }
  101207. }
  101208. },
  101209. enumerable: true,
  101210. configurable: true
  101211. });
  101212. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  101213. /**
  101214. * If the ray of the LaserPointer should be displayed.
  101215. */
  101216. get: function () {
  101217. return this._displayLaserPointer;
  101218. },
  101219. /**
  101220. * Sets if the ray of the LaserPointer should be displayed.
  101221. */
  101222. set: function (value) {
  101223. this._displayLaserPointer = value;
  101224. if (!value) {
  101225. if (this._rightController) {
  101226. this._rightController._deactivatePointer();
  101227. this._rightController._gazeTracker.isVisible = false;
  101228. }
  101229. if (this._leftController) {
  101230. this._leftController._deactivatePointer();
  101231. this._leftController._gazeTracker.isVisible = false;
  101232. }
  101233. }
  101234. else {
  101235. if (this._rightController) {
  101236. this._rightController._activatePointer();
  101237. }
  101238. if (this._leftController) {
  101239. this._leftController._activatePointer();
  101240. }
  101241. }
  101242. },
  101243. enumerable: true,
  101244. configurable: true
  101245. });
  101246. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  101247. /**
  101248. * The deviceOrientationCamera used as the camera when not in VR.
  101249. */
  101250. get: function () {
  101251. return this._deviceOrientationCamera;
  101252. },
  101253. enumerable: true,
  101254. configurable: true
  101255. });
  101256. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  101257. /**
  101258. * Based on the current WebVR support, returns the current VR camera used.
  101259. */
  101260. get: function () {
  101261. if (this._webVRready) {
  101262. return this._webVRCamera;
  101263. }
  101264. else {
  101265. return this._scene.activeCamera;
  101266. }
  101267. },
  101268. enumerable: true,
  101269. configurable: true
  101270. });
  101271. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  101272. /**
  101273. * The webVRCamera which is used when in VR.
  101274. */
  101275. get: function () {
  101276. return this._webVRCamera;
  101277. },
  101278. enumerable: true,
  101279. configurable: true
  101280. });
  101281. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  101282. /**
  101283. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  101284. */
  101285. get: function () {
  101286. return this._vrDeviceOrientationCamera;
  101287. },
  101288. enumerable: true,
  101289. configurable: true
  101290. });
  101291. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  101292. get: function () {
  101293. var result = this._cameraGazer._teleportationRequestInitiated
  101294. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  101295. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  101296. return result;
  101297. },
  101298. enumerable: true,
  101299. configurable: true
  101300. });
  101301. // Raised when one of the controller has loaded successfully its associated default mesh
  101302. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  101303. if (this._leftController && this._leftController.webVRController == webVRController) {
  101304. if (webVRController.mesh) {
  101305. this._leftController._setLaserPointerParent(webVRController.mesh);
  101306. }
  101307. }
  101308. if (this._rightController && this._rightController.webVRController == webVRController) {
  101309. if (webVRController.mesh) {
  101310. this._rightController._setLaserPointerParent(webVRController.mesh);
  101311. }
  101312. }
  101313. try {
  101314. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  101315. }
  101316. catch (err) {
  101317. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  101318. }
  101319. };
  101320. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  101321. /**
  101322. * Gets a value indicating if we are currently in VR mode.
  101323. */
  101324. get: function () {
  101325. return this._webVRpresenting || this._fullscreenVRpresenting;
  101326. },
  101327. enumerable: true,
  101328. configurable: true
  101329. });
  101330. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  101331. var vrDisplay = this._scene.getEngine().getVRDevice();
  101332. if (vrDisplay) {
  101333. var wasPresenting = this._webVRpresenting;
  101334. this._webVRpresenting = vrDisplay.isPresenting;
  101335. if (wasPresenting && !this._webVRpresenting)
  101336. this.exitVR();
  101337. }
  101338. else {
  101339. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  101340. }
  101341. this.updateButtonVisibility();
  101342. };
  101343. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  101344. this._webVRsupported = eventArgs.vrSupported;
  101345. this._webVRready = !!eventArgs.vrDisplay;
  101346. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  101347. this.updateButtonVisibility();
  101348. };
  101349. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  101350. if (this._canvas && !this._useCustomVRButton) {
  101351. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  101352. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  101353. }
  101354. };
  101355. VRExperienceHelper.prototype.displayVRButton = function () {
  101356. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  101357. document.body.appendChild(this._btnVR);
  101358. this._btnVRDisplayed = true;
  101359. }
  101360. };
  101361. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  101362. if (!this._btnVR || this._useCustomVRButton) {
  101363. return;
  101364. }
  101365. this._btnVR.className = "babylonVRicon";
  101366. if (this.isInVRMode) {
  101367. this._btnVR.className += " vrdisplaypresenting";
  101368. }
  101369. else {
  101370. if (this._webVRready)
  101371. this._btnVR.className += " vrdisplayready";
  101372. if (this._webVRsupported)
  101373. this._btnVR.className += " vrdisplaysupported";
  101374. if (this._webVRrequesting)
  101375. this._btnVR.className += " vrdisplayrequesting";
  101376. }
  101377. };
  101378. /**
  101379. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  101380. * Otherwise, will use the fullscreen API.
  101381. */
  101382. VRExperienceHelper.prototype.enterVR = function () {
  101383. if (this.onEnteringVRObservable) {
  101384. try {
  101385. this.onEnteringVRObservable.notifyObservers(this);
  101386. }
  101387. catch (err) {
  101388. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  101389. }
  101390. }
  101391. if (this._scene.activeCamera) {
  101392. this._position = this._scene.activeCamera.position.clone();
  101393. // make sure that we return to the last active camera
  101394. this._existingCamera = this._scene.activeCamera;
  101395. }
  101396. if (this._webVRrequesting)
  101397. return;
  101398. // If WebVR is supported and a headset is connected
  101399. if (this._webVRready) {
  101400. if (!this._webVRpresenting) {
  101401. this._webVRCamera.position = this._position;
  101402. this._scene.activeCamera = this._webVRCamera;
  101403. }
  101404. }
  101405. else if (this._vrDeviceOrientationCamera) {
  101406. this._vrDeviceOrientationCamera.position = this._position;
  101407. if (this._scene.activeCamera) {
  101408. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  101409. }
  101410. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  101411. this._scene.getEngine().switchFullscreen(true);
  101412. this.updateButtonVisibility();
  101413. }
  101414. if (this._scene.activeCamera && this._canvas) {
  101415. this._scene.activeCamera.attachControl(this._canvas);
  101416. }
  101417. if (this._interactionsEnabled) {
  101418. this._scene.registerBeforeRender(this.beforeRender);
  101419. }
  101420. this._hasEnteredVR = true;
  101421. };
  101422. /**
  101423. * Attempt to exit VR, or fullscreen.
  101424. */
  101425. VRExperienceHelper.prototype.exitVR = function () {
  101426. if (this._hasEnteredVR) {
  101427. if (this.onExitingVRObservable) {
  101428. try {
  101429. this.onExitingVRObservable.notifyObservers(this);
  101430. }
  101431. catch (err) {
  101432. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  101433. }
  101434. }
  101435. if (this._webVRpresenting) {
  101436. this._scene.getEngine().disableVR();
  101437. }
  101438. if (this._scene.activeCamera) {
  101439. this._position = this._scene.activeCamera.position.clone();
  101440. }
  101441. if (this._deviceOrientationCamera) {
  101442. this._deviceOrientationCamera.position = this._position;
  101443. this._scene.activeCamera = this._deviceOrientationCamera;
  101444. if (this._canvas) {
  101445. this._scene.activeCamera.attachControl(this._canvas);
  101446. }
  101447. }
  101448. else if (this._existingCamera) {
  101449. this._existingCamera.position = this._position;
  101450. this._scene.activeCamera = this._existingCamera;
  101451. }
  101452. this.updateButtonVisibility();
  101453. if (this._interactionsEnabled) {
  101454. this._scene.unregisterBeforeRender(this.beforeRender);
  101455. this._cameraGazer._gazeTracker.isVisible = false;
  101456. if (this._leftController) {
  101457. this._leftController._gazeTracker.isVisible = false;
  101458. }
  101459. if (this._rightController) {
  101460. this._rightController._gazeTracker.isVisible = false;
  101461. }
  101462. }
  101463. // resize to update width and height when exiting vr exits fullscreen
  101464. this._scene.getEngine().resize();
  101465. this._hasEnteredVR = false;
  101466. }
  101467. };
  101468. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  101469. /**
  101470. * The position of the vr experience helper.
  101471. */
  101472. get: function () {
  101473. return this._position;
  101474. },
  101475. /**
  101476. * Sets the position of the vr experience helper.
  101477. */
  101478. set: function (value) {
  101479. this._position = value;
  101480. if (this._scene.activeCamera) {
  101481. this._scene.activeCamera.position = value;
  101482. }
  101483. },
  101484. enumerable: true,
  101485. configurable: true
  101486. });
  101487. /**
  101488. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  101489. */
  101490. VRExperienceHelper.prototype.enableInteractions = function () {
  101491. var _this = this;
  101492. if (!this._interactionsEnabled) {
  101493. this._interactionsRequested = true;
  101494. if (this._leftController) {
  101495. this._enableInteractionOnController(this._leftController);
  101496. }
  101497. if (this._rightController) {
  101498. this._enableInteractionOnController(this._rightController);
  101499. }
  101500. this.raySelectionPredicate = function (mesh) {
  101501. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  101502. };
  101503. this.meshSelectionPredicate = function (mesh) {
  101504. return true;
  101505. };
  101506. this._raySelectionPredicate = function (mesh) {
  101507. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  101508. && mesh.name.indexOf("teleportationTarget") === -1
  101509. && mesh.name.indexOf("torusTeleportation") === -1)) {
  101510. return _this.raySelectionPredicate(mesh);
  101511. }
  101512. return false;
  101513. };
  101514. this._interactionsEnabled = true;
  101515. }
  101516. };
  101517. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  101518. get: function () {
  101519. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  101520. },
  101521. enumerable: true,
  101522. configurable: true
  101523. });
  101524. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  101525. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  101526. if (this._floorMeshesCollection[i].id === mesh.id) {
  101527. return true;
  101528. }
  101529. }
  101530. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  101531. return true;
  101532. }
  101533. return false;
  101534. };
  101535. /**
  101536. * Adds a floor mesh to be used for teleportation.
  101537. * @param floorMesh the mesh to be used for teleportation.
  101538. */
  101539. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  101540. if (!this._floorMeshesCollection) {
  101541. return;
  101542. }
  101543. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  101544. return;
  101545. }
  101546. this._floorMeshesCollection.push(floorMesh);
  101547. };
  101548. /**
  101549. * Removes a floor mesh from being used for teleportation.
  101550. * @param floorMesh the mesh to be removed.
  101551. */
  101552. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  101553. if (!this._floorMeshesCollection) {
  101554. return;
  101555. }
  101556. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  101557. if (meshIndex !== -1) {
  101558. this._floorMeshesCollection.splice(meshIndex, 1);
  101559. }
  101560. };
  101561. /**
  101562. * Enables interactions and teleportation using the VR controllers and gaze.
  101563. * @param vrTeleportationOptions options to modify teleportation behavior.
  101564. */
  101565. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  101566. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  101567. if (!this._teleportationInitialized) {
  101568. this._teleportationRequested = true;
  101569. this.enableInteractions();
  101570. if (vrTeleportationOptions.floorMeshName) {
  101571. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  101572. }
  101573. if (vrTeleportationOptions.floorMeshes) {
  101574. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  101575. }
  101576. if (this._leftController != null) {
  101577. this._enableTeleportationOnController(this._leftController);
  101578. }
  101579. if (this._rightController != null) {
  101580. this._enableTeleportationOnController(this._rightController);
  101581. }
  101582. // Creates an image processing post process for the vignette not relying
  101583. // on the main scene configuration for image processing to reduce setup and spaces
  101584. // (gamma/linear) conflicts.
  101585. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  101586. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  101587. imageProcessingConfiguration.vignetteEnabled = true;
  101588. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  101589. this._webVRCamera.detachPostProcess(this._postProcessMove);
  101590. this._teleportationInitialized = true;
  101591. if (this._isDefaultTeleportationTarget) {
  101592. this._createTeleportationCircles();
  101593. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  101594. }
  101595. }
  101596. };
  101597. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  101598. var _this = this;
  101599. var controllerMesh = controller.webVRController.mesh;
  101600. if (controllerMesh) {
  101601. controller._interactionsEnabled = true;
  101602. controller._activatePointer();
  101603. if (this.webVROptions.laserToggle) {
  101604. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  101605. // Enabling / disabling laserPointer
  101606. if (_this._displayLaserPointer && stateObject.value === 1) {
  101607. if (controller._activePointer) {
  101608. controller._deactivatePointer();
  101609. }
  101610. else {
  101611. controller._activatePointer();
  101612. }
  101613. if (_this.displayGaze) {
  101614. controller._gazeTracker.isVisible = controller._activePointer;
  101615. }
  101616. }
  101617. });
  101618. }
  101619. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  101620. var gazer = controller;
  101621. if (_this._noControllerIsActive) {
  101622. gazer = _this._cameraGazer;
  101623. }
  101624. if (!gazer._pointerDownOnMeshAsked) {
  101625. if (stateObject.value > _this._padSensibilityUp) {
  101626. gazer._selectionPointerDown();
  101627. }
  101628. }
  101629. else if (stateObject.value < _this._padSensibilityDown) {
  101630. gazer._selectionPointerUp();
  101631. }
  101632. });
  101633. }
  101634. };
  101635. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  101636. // Dont teleport if another gaze already requested teleportation
  101637. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  101638. return;
  101639. }
  101640. if (!gazer._teleportationRequestInitiated) {
  101641. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  101642. gazer._activatePointer();
  101643. gazer._teleportationRequestInitiated = true;
  101644. }
  101645. }
  101646. else {
  101647. // Listening to the proper controller values changes to confirm teleportation
  101648. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  101649. if (this._teleportActive) {
  101650. this.teleportCamera(this._haloCenter);
  101651. }
  101652. gazer._teleportationRequestInitiated = false;
  101653. }
  101654. }
  101655. };
  101656. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  101657. // Only rotate when user is not currently selecting a teleportation location
  101658. if (gazer._teleportationRequestInitiated) {
  101659. return;
  101660. }
  101661. if (!gazer._rotationLeftAsked) {
  101662. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  101663. gazer._rotationLeftAsked = true;
  101664. if (this._rotationAllowed) {
  101665. this._rotateCamera(false);
  101666. }
  101667. }
  101668. }
  101669. else {
  101670. if (stateObject.x > -this._padSensibilityDown) {
  101671. gazer._rotationLeftAsked = false;
  101672. }
  101673. }
  101674. if (!gazer._rotationRightAsked) {
  101675. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  101676. gazer._rotationRightAsked = true;
  101677. if (this._rotationAllowed) {
  101678. this._rotateCamera(true);
  101679. }
  101680. }
  101681. }
  101682. else {
  101683. if (stateObject.x < this._padSensibilityDown) {
  101684. gazer._rotationRightAsked = false;
  101685. }
  101686. }
  101687. };
  101688. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  101689. // Only teleport backwards when user is not currently selecting a teleportation location
  101690. if (gazer._teleportationRequestInitiated) {
  101691. return;
  101692. }
  101693. // Teleport backwards
  101694. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  101695. if (!gazer._teleportationBackRequestInitiated) {
  101696. if (!this.currentVRCamera) {
  101697. return;
  101698. }
  101699. // Get rotation and position of the current camera
  101700. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  101701. var position = this.currentVRCamera.position;
  101702. // If the camera has device position, use that instead
  101703. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  101704. rotation = this.currentVRCamera.deviceRotationQuaternion;
  101705. position = this.currentVRCamera.devicePosition;
  101706. }
  101707. // Get matrix with only the y rotation of the device rotation
  101708. rotation.toEulerAnglesToRef(this._workingVector);
  101709. this._workingVector.z = 0;
  101710. this._workingVector.x = 0;
  101711. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  101712. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  101713. // Rotate backwards ray by device rotation to cast at the ground behind the user
  101714. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  101715. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  101716. var ray = new BABYLON.Ray(position, this._workingVector);
  101717. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  101718. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  101719. this.teleportCamera(hit.pickedPoint);
  101720. }
  101721. gazer._teleportationBackRequestInitiated = true;
  101722. }
  101723. }
  101724. else {
  101725. gazer._teleportationBackRequestInitiated = false;
  101726. }
  101727. };
  101728. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  101729. var _this = this;
  101730. var controllerMesh = controller.webVRController.mesh;
  101731. if (controllerMesh) {
  101732. if (!controller._interactionsEnabled) {
  101733. this._enableInteractionOnController(controller);
  101734. }
  101735. controller._interactionsEnabled = true;
  101736. controller._teleportationEnabled = true;
  101737. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  101738. controller._dpadPressed = false;
  101739. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  101740. controller._dpadPressed = stateObject.pressed;
  101741. if (!controller._dpadPressed) {
  101742. controller._rotationLeftAsked = false;
  101743. controller._rotationRightAsked = false;
  101744. controller._teleportationBackRequestInitiated = false;
  101745. }
  101746. });
  101747. }
  101748. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  101749. if (_this.teleportationEnabled) {
  101750. _this._checkTeleportBackwards(stateObject, controller);
  101751. _this._checkTeleportWithRay(stateObject, controller);
  101752. }
  101753. _this._checkRotate(stateObject, controller);
  101754. });
  101755. }
  101756. };
  101757. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  101758. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  101759. this._teleportationTarget.isPickable = false;
  101760. var length = 512;
  101761. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  101762. dynamicTexture.hasAlpha = true;
  101763. var context = dynamicTexture.getContext();
  101764. var centerX = length / 2;
  101765. var centerY = length / 2;
  101766. var radius = 200;
  101767. context.beginPath();
  101768. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  101769. context.fillStyle = this._teleportationFillColor;
  101770. context.fill();
  101771. context.lineWidth = 10;
  101772. context.strokeStyle = this._teleportationBorderColor;
  101773. context.stroke();
  101774. context.closePath();
  101775. dynamicTexture.update();
  101776. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  101777. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  101778. this._teleportationTarget.material = teleportationCircleMaterial;
  101779. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  101780. torus.isPickable = false;
  101781. torus.parent = this._teleportationTarget;
  101782. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101783. var keys = [];
  101784. keys.push({
  101785. frame: 0,
  101786. value: 0
  101787. });
  101788. keys.push({
  101789. frame: 30,
  101790. value: 0.4
  101791. });
  101792. keys.push({
  101793. frame: 60,
  101794. value: 0
  101795. });
  101796. animationInnerCircle.setKeys(keys);
  101797. var easingFunction = new BABYLON.SineEase();
  101798. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  101799. animationInnerCircle.setEasingFunction(easingFunction);
  101800. torus.animations = [];
  101801. torus.animations.push(animationInnerCircle);
  101802. this._scene.beginAnimation(torus, 0, 60, true);
  101803. this._hideTeleportationTarget();
  101804. };
  101805. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  101806. this._teleportActive = true;
  101807. if (this._teleportationInitialized) {
  101808. this._teleportationTarget.isVisible = true;
  101809. if (this._isDefaultTeleportationTarget) {
  101810. this._teleportationTarget.getChildren()[0].isVisible = true;
  101811. }
  101812. }
  101813. };
  101814. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  101815. this._teleportActive = false;
  101816. if (this._teleportationInitialized) {
  101817. this._teleportationTarget.isVisible = false;
  101818. if (this._isDefaultTeleportationTarget) {
  101819. this._teleportationTarget.getChildren()[0].isVisible = false;
  101820. }
  101821. }
  101822. };
  101823. VRExperienceHelper.prototype._rotateCamera = function (right) {
  101824. var _this = this;
  101825. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101826. return;
  101827. }
  101828. if (right) {
  101829. this._rotationAngle++;
  101830. }
  101831. else {
  101832. this._rotationAngle--;
  101833. }
  101834. this.currentVRCamera.animations = [];
  101835. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  101836. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101837. var animationRotationKeys = [];
  101838. animationRotationKeys.push({
  101839. frame: 0,
  101840. value: this.currentVRCamera.rotationQuaternion
  101841. });
  101842. animationRotationKeys.push({
  101843. frame: 6,
  101844. value: target
  101845. });
  101846. animationRotation.setKeys(animationRotationKeys);
  101847. animationRotation.setEasingFunction(this._circleEase);
  101848. this.currentVRCamera.animations.push(animationRotation);
  101849. this._postProcessMove.animations = [];
  101850. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101851. var vignetteWeightKeys = [];
  101852. vignetteWeightKeys.push({
  101853. frame: 0,
  101854. value: 0
  101855. });
  101856. vignetteWeightKeys.push({
  101857. frame: 3,
  101858. value: 4
  101859. });
  101860. vignetteWeightKeys.push({
  101861. frame: 6,
  101862. value: 0
  101863. });
  101864. animationPP.setKeys(vignetteWeightKeys);
  101865. animationPP.setEasingFunction(this._circleEase);
  101866. this._postProcessMove.animations.push(animationPP);
  101867. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101868. var vignetteStretchKeys = [];
  101869. vignetteStretchKeys.push({
  101870. frame: 0,
  101871. value: 0
  101872. });
  101873. vignetteStretchKeys.push({
  101874. frame: 3,
  101875. value: 10
  101876. });
  101877. vignetteStretchKeys.push({
  101878. frame: 6,
  101879. value: 0
  101880. });
  101881. animationPP2.setKeys(vignetteStretchKeys);
  101882. animationPP2.setEasingFunction(this._circleEase);
  101883. this._postProcessMove.animations.push(animationPP2);
  101884. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101885. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101886. this._postProcessMove.samples = 4;
  101887. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101888. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  101889. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101890. });
  101891. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  101892. };
  101893. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  101894. if (hit.pickedPoint) {
  101895. if (gazer._teleportationRequestInitiated) {
  101896. this._displayTeleportationTarget();
  101897. this._haloCenter.copyFrom(hit.pickedPoint);
  101898. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  101899. }
  101900. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  101901. if (pickNormal) {
  101902. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  101903. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  101904. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  101905. }
  101906. this._teleportationTarget.position.y += 0.1;
  101907. }
  101908. };
  101909. /**
  101910. * Teleports the users feet to the desired location
  101911. * @param location The location where the user's feet should be placed
  101912. */
  101913. VRExperienceHelper.prototype.teleportCamera = function (location) {
  101914. var _this = this;
  101915. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  101916. return;
  101917. }
  101918. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  101919. // offset of the headset from the anchor.
  101920. if (this.webVRCamera.leftCamera) {
  101921. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  101922. this._workingVector.subtractInPlace(this.webVRCamera.position);
  101923. location.subtractToRef(this._workingVector, this._workingVector);
  101924. }
  101925. else {
  101926. this._workingVector.copyFrom(location);
  101927. }
  101928. // Add height to account for user's height offset
  101929. if (this.isInVRMode) {
  101930. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  101931. }
  101932. else {
  101933. this._workingVector.y += this._defaultHeight;
  101934. }
  101935. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  101936. // Create animation from the camera's position to the new location
  101937. this.currentVRCamera.animations = [];
  101938. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101939. var animationCameraTeleportationKeys = [{
  101940. frame: 0,
  101941. value: this.currentVRCamera.position
  101942. },
  101943. {
  101944. frame: 11,
  101945. value: this._workingVector
  101946. }
  101947. ];
  101948. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  101949. animationCameraTeleportation.setEasingFunction(this._circleEase);
  101950. this.currentVRCamera.animations.push(animationCameraTeleportation);
  101951. this._postProcessMove.animations = [];
  101952. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101953. var vignetteWeightKeys = [];
  101954. vignetteWeightKeys.push({
  101955. frame: 0,
  101956. value: 0
  101957. });
  101958. vignetteWeightKeys.push({
  101959. frame: 5,
  101960. value: 8
  101961. });
  101962. vignetteWeightKeys.push({
  101963. frame: 11,
  101964. value: 0
  101965. });
  101966. animationPP.setKeys(vignetteWeightKeys);
  101967. this._postProcessMove.animations.push(animationPP);
  101968. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  101969. var vignetteStretchKeys = [];
  101970. vignetteStretchKeys.push({
  101971. frame: 0,
  101972. value: 0
  101973. });
  101974. vignetteStretchKeys.push({
  101975. frame: 5,
  101976. value: 10
  101977. });
  101978. vignetteStretchKeys.push({
  101979. frame: 11,
  101980. value: 0
  101981. });
  101982. animationPP2.setKeys(vignetteStretchKeys);
  101983. this._postProcessMove.animations.push(animationPP2);
  101984. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  101985. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  101986. this._webVRCamera.attachPostProcess(this._postProcessMove);
  101987. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  101988. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  101989. });
  101990. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  101991. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  101992. });
  101993. this._hideTeleportationTarget();
  101994. };
  101995. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  101996. if (normal) {
  101997. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  101998. if (angle < Math.PI / 2) {
  101999. normal.scaleInPlace(-1);
  102000. }
  102001. }
  102002. return normal;
  102003. };
  102004. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  102005. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  102006. return;
  102007. }
  102008. var ray = gazer._getForwardRay(this._rayLength);
  102009. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  102010. if (hit) {
  102011. // Populate the contrllers mesh that can be used for drag/drop
  102012. if (gazer._laserPointer) {
  102013. hit.originMesh = gazer._laserPointer.parent;
  102014. }
  102015. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  102016. }
  102017. gazer._currentHit = hit;
  102018. // Moving the gazeTracker on the mesh face targetted
  102019. if (hit && hit.pickedPoint) {
  102020. if (this._displayGaze) {
  102021. var multiplier = 1;
  102022. gazer._gazeTracker.isVisible = true;
  102023. if (gazer._isActionableMesh) {
  102024. multiplier = 3;
  102025. }
  102026. if (this.updateGazeTrackerScale) {
  102027. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  102028. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  102029. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  102030. }
  102031. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  102032. // To avoid z-fighting
  102033. var deltaFighting = 0.002;
  102034. if (pickNormal) {
  102035. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  102036. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  102037. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  102038. }
  102039. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  102040. if (gazer._gazeTracker.position.x < 0) {
  102041. gazer._gazeTracker.position.x += deltaFighting;
  102042. }
  102043. else {
  102044. gazer._gazeTracker.position.x -= deltaFighting;
  102045. }
  102046. if (gazer._gazeTracker.position.y < 0) {
  102047. gazer._gazeTracker.position.y += deltaFighting;
  102048. }
  102049. else {
  102050. gazer._gazeTracker.position.y -= deltaFighting;
  102051. }
  102052. if (gazer._gazeTracker.position.z < 0) {
  102053. gazer._gazeTracker.position.z += deltaFighting;
  102054. }
  102055. else {
  102056. gazer._gazeTracker.position.z -= deltaFighting;
  102057. }
  102058. }
  102059. // Changing the size of the laser pointer based on the distance from the targetted point
  102060. gazer._updatePointerDistance(hit.distance);
  102061. }
  102062. else {
  102063. gazer._updatePointerDistance();
  102064. gazer._gazeTracker.isVisible = false;
  102065. }
  102066. if (hit && hit.pickedMesh) {
  102067. // The object selected is the floor, we're in a teleportation scenario
  102068. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  102069. // Moving the teleportation area to this targetted point
  102070. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  102071. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  102072. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102073. }
  102074. gazer._currentMeshSelected = null;
  102075. if (gazer._teleportationRequestInitiated) {
  102076. this._moveTeleportationSelectorTo(hit, gazer, ray);
  102077. }
  102078. return;
  102079. }
  102080. // If not, we're in a selection scenario
  102081. //this._teleportationAllowed = false;
  102082. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  102083. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  102084. this.onNewMeshPicked.notifyObservers(hit);
  102085. gazer._currentMeshSelected = hit.pickedMesh;
  102086. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  102087. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  102088. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  102089. gazer._isActionableMesh = true;
  102090. }
  102091. else {
  102092. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102093. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102094. gazer._isActionableMesh = false;
  102095. }
  102096. try {
  102097. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  102098. }
  102099. catch (err) {
  102100. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  102101. }
  102102. }
  102103. else {
  102104. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102105. gazer._currentMeshSelected = null;
  102106. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102107. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102108. }
  102109. }
  102110. }
  102111. else {
  102112. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  102113. gazer._currentMeshSelected = null;
  102114. //this._teleportationAllowed = false;
  102115. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102116. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  102117. }
  102118. };
  102119. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  102120. if (mesh) {
  102121. this.onSelectedMeshUnselected.notifyObservers(mesh);
  102122. }
  102123. };
  102124. /**
  102125. * Sets the color of the laser ray from the vr controllers.
  102126. * @param color new color for the ray.
  102127. */
  102128. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  102129. if (this._leftController) {
  102130. this._leftController._setLaserPointerColor(color);
  102131. }
  102132. if (this._rightController) {
  102133. this._rightController._setLaserPointerColor(color);
  102134. }
  102135. };
  102136. /**
  102137. * Sets the color of the ray from the vr headsets gaze.
  102138. * @param color new color for the ray.
  102139. */
  102140. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  102141. if (!this._cameraGazer._gazeTracker.material) {
  102142. return;
  102143. }
  102144. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  102145. if (this._leftController) {
  102146. this._leftController._gazeTracker.material.emissiveColor = color;
  102147. }
  102148. if (this._rightController) {
  102149. this._rightController._gazeTracker.material.emissiveColor = color;
  102150. }
  102151. };
  102152. /**
  102153. * Exits VR and disposes of the vr experience helper
  102154. */
  102155. VRExperienceHelper.prototype.dispose = function () {
  102156. if (this.isInVRMode) {
  102157. this.exitVR();
  102158. }
  102159. if (this._postProcessMove) {
  102160. this._postProcessMove.dispose();
  102161. }
  102162. if (this._webVRCamera) {
  102163. this._webVRCamera.dispose();
  102164. }
  102165. if (this._vrDeviceOrientationCamera) {
  102166. this._vrDeviceOrientationCamera.dispose();
  102167. }
  102168. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  102169. document.body.removeChild(this._btnVR);
  102170. }
  102171. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  102172. this._deviceOrientationCamera.dispose();
  102173. }
  102174. if (this._cameraGazer) {
  102175. this._cameraGazer.dispose();
  102176. }
  102177. if (this._leftController) {
  102178. this._leftController.dispose();
  102179. }
  102180. if (this._rightController) {
  102181. this._rightController.dispose();
  102182. }
  102183. if (this._teleportationTarget) {
  102184. this._teleportationTarget.dispose();
  102185. }
  102186. this._floorMeshesCollection = [];
  102187. document.removeEventListener("keydown", this._onKeyDown);
  102188. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102189. window.removeEventListener("resize", this._onResize);
  102190. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  102191. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  102192. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  102193. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  102194. document.onmsfullscreenchange = null;
  102195. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  102196. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  102197. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  102198. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  102199. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  102200. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  102201. this._scene.unregisterBeforeRender(this.beforeRender);
  102202. };
  102203. /**
  102204. * Gets the name of the VRExperienceHelper class
  102205. * @returns "VRExperienceHelper"
  102206. */
  102207. VRExperienceHelper.prototype.getClassName = function () {
  102208. return "VRExperienceHelper";
  102209. };
  102210. return VRExperienceHelper;
  102211. }());
  102212. BABYLON.VRExperienceHelper = VRExperienceHelper;
  102213. })(BABYLON || (BABYLON = {}));
  102214. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  102215. // Mainly based on these 2 articles :
  102216. // 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
  102217. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  102218. var BABYLON;
  102219. (function (BABYLON) {
  102220. /**
  102221. * Defines the potential axis of a Joystick
  102222. */
  102223. var JoystickAxis;
  102224. (function (JoystickAxis) {
  102225. /** X axis */
  102226. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  102227. /** Y axis */
  102228. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  102229. /** Z axis */
  102230. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  102231. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  102232. /**
  102233. * Class used to define virtual joystick (used in touch mode)
  102234. */
  102235. var VirtualJoystick = /** @class */ (function () {
  102236. /**
  102237. * Creates a new virtual joystick
  102238. * @param leftJoystick defines that the joystick is for left hand (false by default)
  102239. */
  102240. function VirtualJoystick(leftJoystick) {
  102241. var _this = this;
  102242. if (leftJoystick) {
  102243. this._leftJoystick = true;
  102244. }
  102245. else {
  102246. this._leftJoystick = false;
  102247. }
  102248. VirtualJoystick._globalJoystickIndex++;
  102249. // By default left & right arrow keys are moving the X
  102250. // and up & down keys are moving the Y
  102251. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102252. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102253. this.reverseLeftRight = false;
  102254. this.reverseUpDown = false;
  102255. // collections of pointers
  102256. this._touches = new BABYLON.StringDictionary();
  102257. this.deltaPosition = BABYLON.Vector3.Zero();
  102258. this._joystickSensibility = 25;
  102259. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102260. this._onResize = function (evt) {
  102261. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102262. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102263. if (VirtualJoystick.vjCanvas) {
  102264. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  102265. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  102266. }
  102267. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  102268. };
  102269. // injecting a canvas element on top of the canvas 3D game
  102270. if (!VirtualJoystick.vjCanvas) {
  102271. window.addEventListener("resize", this._onResize, false);
  102272. VirtualJoystick.vjCanvas = document.createElement("canvas");
  102273. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  102274. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  102275. VirtualJoystick.vjCanvas.width = window.innerWidth;
  102276. VirtualJoystick.vjCanvas.height = window.innerHeight;
  102277. VirtualJoystick.vjCanvas.style.width = "100%";
  102278. VirtualJoystick.vjCanvas.style.height = "100%";
  102279. VirtualJoystick.vjCanvas.style.position = "absolute";
  102280. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  102281. VirtualJoystick.vjCanvas.style.top = "0px";
  102282. VirtualJoystick.vjCanvas.style.left = "0px";
  102283. VirtualJoystick.vjCanvas.style.zIndex = "5";
  102284. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  102285. // Support for jQuery PEP polyfill
  102286. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  102287. var context = VirtualJoystick.vjCanvas.getContext('2d');
  102288. if (!context) {
  102289. throw new Error("Unable to create canvas for virtual joystick");
  102290. }
  102291. VirtualJoystick.vjCanvasContext = context;
  102292. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  102293. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102294. document.body.appendChild(VirtualJoystick.vjCanvas);
  102295. }
  102296. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  102297. this.pressed = false;
  102298. // default joystick color
  102299. this._joystickColor = "cyan";
  102300. this._joystickPointerID = -1;
  102301. // current joystick position
  102302. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  102303. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  102304. // origin joystick position
  102305. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  102306. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  102307. this._onPointerDownHandlerRef = function (evt) {
  102308. _this._onPointerDown(evt);
  102309. };
  102310. this._onPointerMoveHandlerRef = function (evt) {
  102311. _this._onPointerMove(evt);
  102312. };
  102313. this._onPointerUpHandlerRef = function (evt) {
  102314. _this._onPointerUp(evt);
  102315. };
  102316. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  102317. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  102318. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  102319. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  102320. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  102321. evt.preventDefault(); // Disables system menu
  102322. }, false);
  102323. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102324. }
  102325. /**
  102326. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  102327. * @param newJoystickSensibility defines the new sensibility
  102328. */
  102329. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  102330. this._joystickSensibility = newJoystickSensibility;
  102331. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  102332. };
  102333. VirtualJoystick.prototype._onPointerDown = function (e) {
  102334. var positionOnScreenCondition;
  102335. e.preventDefault();
  102336. if (this._leftJoystick === true) {
  102337. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  102338. }
  102339. else {
  102340. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  102341. }
  102342. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  102343. // First contact will be dedicated to the virtual joystick
  102344. this._joystickPointerID = e.pointerId;
  102345. this._joystickPointerStartPos.x = e.clientX;
  102346. this._joystickPointerStartPos.y = e.clientY;
  102347. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  102348. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  102349. this._deltaJoystickVector.x = 0;
  102350. this._deltaJoystickVector.y = 0;
  102351. this.pressed = true;
  102352. this._touches.add(e.pointerId.toString(), e);
  102353. }
  102354. else {
  102355. // You can only trigger the action buttons with a joystick declared
  102356. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  102357. this._action();
  102358. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  102359. }
  102360. }
  102361. };
  102362. VirtualJoystick.prototype._onPointerMove = function (e) {
  102363. // If the current pointer is the one associated to the joystick (first touch contact)
  102364. if (this._joystickPointerID == e.pointerId) {
  102365. this._joystickPointerPos.x = e.clientX;
  102366. this._joystickPointerPos.y = e.clientY;
  102367. this._deltaJoystickVector = this._joystickPointerPos.clone();
  102368. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  102369. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  102370. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  102371. switch (this._axisTargetedByLeftAndRight) {
  102372. case JoystickAxis.X:
  102373. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  102374. break;
  102375. case JoystickAxis.Y:
  102376. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  102377. break;
  102378. case JoystickAxis.Z:
  102379. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  102380. break;
  102381. }
  102382. var directionUpDown = this.reverseUpDown ? 1 : -1;
  102383. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  102384. switch (this._axisTargetedByUpAndDown) {
  102385. case JoystickAxis.X:
  102386. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  102387. break;
  102388. case JoystickAxis.Y:
  102389. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  102390. break;
  102391. case JoystickAxis.Z:
  102392. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  102393. break;
  102394. }
  102395. }
  102396. else {
  102397. var data = this._touches.get(e.pointerId.toString());
  102398. if (data) {
  102399. data.x = e.clientX;
  102400. data.y = e.clientY;
  102401. }
  102402. }
  102403. };
  102404. VirtualJoystick.prototype._onPointerUp = function (e) {
  102405. if (this._joystickPointerID == e.pointerId) {
  102406. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  102407. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  102408. this._joystickPointerID = -1;
  102409. this.pressed = false;
  102410. }
  102411. else {
  102412. var touch = this._touches.get(e.pointerId.toString());
  102413. if (touch) {
  102414. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102415. }
  102416. }
  102417. this._deltaJoystickVector.x = 0;
  102418. this._deltaJoystickVector.y = 0;
  102419. this._touches.remove(e.pointerId.toString());
  102420. };
  102421. /**
  102422. * Change the color of the virtual joystick
  102423. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  102424. */
  102425. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  102426. this._joystickColor = newColor;
  102427. };
  102428. /**
  102429. * Defines a callback to call when the joystick is touched
  102430. * @param action defines the callback
  102431. */
  102432. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  102433. this._action = action;
  102434. };
  102435. /**
  102436. * Defines which axis you'd like to control for left & right
  102437. * @param axis defines the axis to use
  102438. */
  102439. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  102440. switch (axis) {
  102441. case JoystickAxis.X:
  102442. case JoystickAxis.Y:
  102443. case JoystickAxis.Z:
  102444. this._axisTargetedByLeftAndRight = axis;
  102445. break;
  102446. default:
  102447. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  102448. break;
  102449. }
  102450. };
  102451. /**
  102452. * Defines which axis you'd like to control for up & down
  102453. * @param axis defines the axis to use
  102454. */
  102455. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  102456. switch (axis) {
  102457. case JoystickAxis.X:
  102458. case JoystickAxis.Y:
  102459. case JoystickAxis.Z:
  102460. this._axisTargetedByUpAndDown = axis;
  102461. break;
  102462. default:
  102463. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  102464. break;
  102465. }
  102466. };
  102467. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  102468. var _this = this;
  102469. if (this.pressed) {
  102470. this._touches.forEach(function (key, touch) {
  102471. if (touch.pointerId === _this._joystickPointerID) {
  102472. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  102473. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  102474. VirtualJoystick.vjCanvasContext.beginPath();
  102475. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102476. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102477. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  102478. VirtualJoystick.vjCanvasContext.stroke();
  102479. VirtualJoystick.vjCanvasContext.closePath();
  102480. VirtualJoystick.vjCanvasContext.beginPath();
  102481. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102482. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  102483. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  102484. VirtualJoystick.vjCanvasContext.stroke();
  102485. VirtualJoystick.vjCanvasContext.closePath();
  102486. VirtualJoystick.vjCanvasContext.beginPath();
  102487. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  102488. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  102489. VirtualJoystick.vjCanvasContext.stroke();
  102490. VirtualJoystick.vjCanvasContext.closePath();
  102491. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  102492. }
  102493. else {
  102494. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  102495. VirtualJoystick.vjCanvasContext.beginPath();
  102496. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  102497. VirtualJoystick.vjCanvasContext.beginPath();
  102498. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  102499. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  102500. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  102501. VirtualJoystick.vjCanvasContext.stroke();
  102502. VirtualJoystick.vjCanvasContext.closePath();
  102503. touch.prevX = touch.x;
  102504. touch.prevY = touch.y;
  102505. }
  102506. ;
  102507. });
  102508. }
  102509. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  102510. };
  102511. /**
  102512. * Release internal HTML canvas
  102513. */
  102514. VirtualJoystick.prototype.releaseCanvas = function () {
  102515. if (VirtualJoystick.vjCanvas) {
  102516. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  102517. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  102518. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  102519. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  102520. window.removeEventListener("resize", this._onResize);
  102521. document.body.removeChild(VirtualJoystick.vjCanvas);
  102522. VirtualJoystick.vjCanvas = null;
  102523. }
  102524. };
  102525. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  102526. VirtualJoystick._globalJoystickIndex = 0;
  102527. return VirtualJoystick;
  102528. }());
  102529. BABYLON.VirtualJoystick = VirtualJoystick;
  102530. })(BABYLON || (BABYLON = {}));
  102531. //# sourceMappingURL=babylon.virtualJoystick.js.map
  102532. var BABYLON;
  102533. (function (BABYLON) {
  102534. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  102535. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  102536. });
  102537. /**
  102538. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  102539. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102540. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102541. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102542. */
  102543. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  102544. __extends(VirtualJoysticksCamera, _super);
  102545. /**
  102546. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  102547. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  102548. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  102549. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  102550. * @param name Define the name of the camera in the scene
  102551. * @param position Define the start position of the camera in the scene
  102552. * @param scene Define the scene the camera belongs to
  102553. */
  102554. function VirtualJoysticksCamera(name, position, scene) {
  102555. var _this = _super.call(this, name, position, scene) || this;
  102556. _this.inputs.addVirtualJoystick();
  102557. return _this;
  102558. }
  102559. /**
  102560. * Gets the current object class name.
  102561. * @return the class name
  102562. */
  102563. VirtualJoysticksCamera.prototype.getClassName = function () {
  102564. return "VirtualJoysticksCamera";
  102565. };
  102566. return VirtualJoysticksCamera;
  102567. }(BABYLON.FreeCamera));
  102568. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  102569. })(BABYLON || (BABYLON = {}));
  102570. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  102571. var BABYLON;
  102572. (function (BABYLON) {
  102573. /**
  102574. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  102575. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  102576. */
  102577. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  102578. function FreeCameraVirtualJoystickInput() {
  102579. }
  102580. /**
  102581. * Gets the left stick of the virtual joystick.
  102582. * @returns The virtual Joystick
  102583. */
  102584. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  102585. return this._leftjoystick;
  102586. };
  102587. /**
  102588. * Gets the right stick of the virtual joystick.
  102589. * @returns The virtual Joystick
  102590. */
  102591. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  102592. return this._rightjoystick;
  102593. };
  102594. /**
  102595. * Update the current camera state depending on the inputs that have been used this frame.
  102596. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  102597. */
  102598. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  102599. if (this._leftjoystick) {
  102600. var camera = this.camera;
  102601. var speed = camera._computeLocalCameraSpeed() * 50;
  102602. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  102603. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  102604. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  102605. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  102606. if (!this._leftjoystick.pressed) {
  102607. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  102608. }
  102609. if (!this._rightjoystick.pressed) {
  102610. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  102611. }
  102612. }
  102613. };
  102614. /**
  102615. * Attach the input controls to a specific dom element to get the input from.
  102616. * @param element Defines the element the controls should be listened from
  102617. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  102618. */
  102619. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  102620. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  102621. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  102622. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  102623. this._leftjoystick.setJoystickSensibility(0.15);
  102624. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  102625. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  102626. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  102627. this._rightjoystick.reverseUpDown = true;
  102628. this._rightjoystick.setJoystickSensibility(0.05);
  102629. this._rightjoystick.setJoystickColor("yellow");
  102630. };
  102631. /**
  102632. * Detach the current controls from the specified dom element.
  102633. * @param element Defines the element to stop listening the inputs from
  102634. */
  102635. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  102636. this._leftjoystick.releaseCanvas();
  102637. this._rightjoystick.releaseCanvas();
  102638. };
  102639. /**
  102640. * Gets the class name of the current intput.
  102641. * @returns the class name
  102642. */
  102643. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  102644. return "FreeCameraVirtualJoystickInput";
  102645. };
  102646. /**
  102647. * Get the friendly name associated with the input class.
  102648. * @returns the input friendly name
  102649. */
  102650. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  102651. return "virtualJoystick";
  102652. };
  102653. return FreeCameraVirtualJoystickInput;
  102654. }());
  102655. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  102656. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  102657. })(BABYLON || (BABYLON = {}));
  102658. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  102659. var BABYLON;
  102660. (function (BABYLON) {
  102661. var SimplificationSettings = /** @class */ (function () {
  102662. function SimplificationSettings(quality, distance, optimizeMesh) {
  102663. this.quality = quality;
  102664. this.distance = distance;
  102665. this.optimizeMesh = optimizeMesh;
  102666. }
  102667. return SimplificationSettings;
  102668. }());
  102669. BABYLON.SimplificationSettings = SimplificationSettings;
  102670. var SimplificationQueue = /** @class */ (function () {
  102671. function SimplificationQueue() {
  102672. this.running = false;
  102673. this._simplificationArray = [];
  102674. }
  102675. SimplificationQueue.prototype.addTask = function (task) {
  102676. this._simplificationArray.push(task);
  102677. };
  102678. SimplificationQueue.prototype.executeNext = function () {
  102679. var task = this._simplificationArray.pop();
  102680. if (task) {
  102681. this.running = true;
  102682. this.runSimplification(task);
  102683. }
  102684. else {
  102685. this.running = false;
  102686. }
  102687. };
  102688. SimplificationQueue.prototype.runSimplification = function (task) {
  102689. var _this = this;
  102690. if (task.parallelProcessing) {
  102691. //parallel simplifier
  102692. task.settings.forEach(function (setting) {
  102693. var simplifier = _this.getSimplifier(task);
  102694. simplifier.simplify(setting, function (newMesh) {
  102695. task.mesh.addLODLevel(setting.distance, newMesh);
  102696. newMesh.isVisible = true;
  102697. //check if it is the last
  102698. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  102699. //all done, run the success callback.
  102700. task.successCallback();
  102701. }
  102702. _this.executeNext();
  102703. });
  102704. });
  102705. }
  102706. else {
  102707. //single simplifier.
  102708. var simplifier = this.getSimplifier(task);
  102709. var runDecimation = function (setting, callback) {
  102710. simplifier.simplify(setting, function (newMesh) {
  102711. task.mesh.addLODLevel(setting.distance, newMesh);
  102712. newMesh.isVisible = true;
  102713. //run the next quality level
  102714. callback();
  102715. });
  102716. };
  102717. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  102718. runDecimation(task.settings[loop.index], function () {
  102719. loop.executeNext();
  102720. });
  102721. }, function () {
  102722. //execution ended, run the success callback.
  102723. if (task.successCallback) {
  102724. task.successCallback();
  102725. }
  102726. _this.executeNext();
  102727. });
  102728. }
  102729. };
  102730. SimplificationQueue.prototype.getSimplifier = function (task) {
  102731. switch (task.simplificationType) {
  102732. case SimplificationType.QUADRATIC:
  102733. default:
  102734. return new QuadraticErrorSimplification(task.mesh);
  102735. }
  102736. };
  102737. return SimplificationQueue;
  102738. }());
  102739. BABYLON.SimplificationQueue = SimplificationQueue;
  102740. /**
  102741. * The implemented types of simplification
  102742. * At the moment only Quadratic Error Decimation is implemented
  102743. */
  102744. var SimplificationType;
  102745. (function (SimplificationType) {
  102746. /** Quadratic error decimation */
  102747. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  102748. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  102749. var DecimationTriangle = /** @class */ (function () {
  102750. function DecimationTriangle(vertices) {
  102751. this.vertices = vertices;
  102752. this.error = new Array(4);
  102753. this.deleted = false;
  102754. this.isDirty = false;
  102755. this.deletePending = false;
  102756. this.borderFactor = 0;
  102757. }
  102758. return DecimationTriangle;
  102759. }());
  102760. BABYLON.DecimationTriangle = DecimationTriangle;
  102761. var DecimationVertex = /** @class */ (function () {
  102762. function DecimationVertex(position, id) {
  102763. this.position = position;
  102764. this.id = id;
  102765. this.isBorder = true;
  102766. this.q = new QuadraticMatrix();
  102767. this.triangleCount = 0;
  102768. this.triangleStart = 0;
  102769. this.originalOffsets = [];
  102770. }
  102771. DecimationVertex.prototype.updatePosition = function (newPosition) {
  102772. this.position.copyFrom(newPosition);
  102773. };
  102774. return DecimationVertex;
  102775. }());
  102776. BABYLON.DecimationVertex = DecimationVertex;
  102777. var QuadraticMatrix = /** @class */ (function () {
  102778. function QuadraticMatrix(data) {
  102779. this.data = new Array(10);
  102780. for (var i = 0; i < 10; ++i) {
  102781. if (data && data[i]) {
  102782. this.data[i] = data[i];
  102783. }
  102784. else {
  102785. this.data[i] = 0;
  102786. }
  102787. }
  102788. }
  102789. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  102790. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  102791. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  102792. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  102793. return det;
  102794. };
  102795. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  102796. for (var i = 0; i < 10; ++i) {
  102797. this.data[i] += matrix.data[i];
  102798. }
  102799. };
  102800. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  102801. for (var i = 0; i < 10; ++i) {
  102802. this.data[i] += data[i];
  102803. }
  102804. };
  102805. QuadraticMatrix.prototype.add = function (matrix) {
  102806. var m = new QuadraticMatrix();
  102807. for (var i = 0; i < 10; ++i) {
  102808. m.data[i] = this.data[i] + matrix.data[i];
  102809. }
  102810. return m;
  102811. };
  102812. QuadraticMatrix.FromData = function (a, b, c, d) {
  102813. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  102814. };
  102815. //returning an array to avoid garbage collection
  102816. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  102817. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  102818. };
  102819. return QuadraticMatrix;
  102820. }());
  102821. BABYLON.QuadraticMatrix = QuadraticMatrix;
  102822. var Reference = /** @class */ (function () {
  102823. function Reference(vertexId, triangleId) {
  102824. this.vertexId = vertexId;
  102825. this.triangleId = triangleId;
  102826. }
  102827. return Reference;
  102828. }());
  102829. BABYLON.Reference = Reference;
  102830. /**
  102831. * An implementation of the Quadratic Error simplification algorithm.
  102832. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  102833. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  102834. * @author RaananW
  102835. */
  102836. var QuadraticErrorSimplification = /** @class */ (function () {
  102837. function QuadraticErrorSimplification(_mesh) {
  102838. this._mesh = _mesh;
  102839. this.syncIterations = 5000;
  102840. this.aggressiveness = 7;
  102841. this.decimationIterations = 100;
  102842. this.boundingBoxEpsilon = BABYLON.Epsilon;
  102843. }
  102844. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  102845. var _this = this;
  102846. this.initDecimatedMesh();
  102847. //iterating through the submeshes array, one after the other.
  102848. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  102849. _this.initWithMesh(loop.index, function () {
  102850. _this.runDecimation(settings, loop.index, function () {
  102851. loop.executeNext();
  102852. });
  102853. }, settings.optimizeMesh);
  102854. }, function () {
  102855. setTimeout(function () {
  102856. successCallback(_this._reconstructedMesh);
  102857. }, 0);
  102858. });
  102859. };
  102860. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  102861. var _this = this;
  102862. var targetCount = ~~(this.triangles.length * settings.quality);
  102863. var deletedTriangles = 0;
  102864. var triangleCount = this.triangles.length;
  102865. var iterationFunction = function (iteration, callback) {
  102866. setTimeout(function () {
  102867. if (iteration % 5 === 0) {
  102868. _this.updateMesh(iteration === 0);
  102869. }
  102870. for (var i = 0; i < _this.triangles.length; ++i) {
  102871. _this.triangles[i].isDirty = false;
  102872. }
  102873. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  102874. var trianglesIterator = function (i) {
  102875. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  102876. var t = _this.triangles[tIdx];
  102877. if (!t)
  102878. return;
  102879. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  102880. return;
  102881. }
  102882. for (var j = 0; j < 3; ++j) {
  102883. if (t.error[j] < threshold) {
  102884. var deleted0 = [];
  102885. var deleted1 = [];
  102886. var v0 = t.vertices[j];
  102887. var v1 = t.vertices[(j + 1) % 3];
  102888. if (v0.isBorder || v1.isBorder)
  102889. continue;
  102890. var p = BABYLON.Vector3.Zero();
  102891. var n = BABYLON.Vector3.Zero();
  102892. var uv = BABYLON.Vector2.Zero();
  102893. var color = new BABYLON.Color4(0, 0, 0, 1);
  102894. _this.calculateError(v0, v1, p, n, uv, color);
  102895. var delTr = new Array();
  102896. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  102897. continue;
  102898. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  102899. continue;
  102900. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  102901. continue;
  102902. var uniqueArray = new Array();
  102903. delTr.forEach(function (deletedT) {
  102904. if (uniqueArray.indexOf(deletedT) === -1) {
  102905. deletedT.deletePending = true;
  102906. uniqueArray.push(deletedT);
  102907. }
  102908. });
  102909. if (uniqueArray.length % 2 !== 0) {
  102910. continue;
  102911. }
  102912. v0.q = v1.q.add(v0.q);
  102913. v0.updatePosition(p);
  102914. var tStart = _this.references.length;
  102915. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  102916. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  102917. var tCount = _this.references.length - tStart;
  102918. if (tCount <= v0.triangleCount) {
  102919. if (tCount) {
  102920. for (var c = 0; c < tCount; c++) {
  102921. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  102922. }
  102923. }
  102924. }
  102925. else {
  102926. v0.triangleStart = tStart;
  102927. }
  102928. v0.triangleCount = tCount;
  102929. break;
  102930. }
  102931. }
  102932. };
  102933. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  102934. }, 0);
  102935. };
  102936. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  102937. if (triangleCount - deletedTriangles <= targetCount)
  102938. loop.breakLoop();
  102939. else {
  102940. iterationFunction(loop.index, function () {
  102941. loop.executeNext();
  102942. });
  102943. }
  102944. }, function () {
  102945. setTimeout(function () {
  102946. //reconstruct this part of the mesh
  102947. _this.reconstructMesh(submeshIndex);
  102948. successCallback();
  102949. }, 0);
  102950. });
  102951. };
  102952. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  102953. var _this = this;
  102954. this.vertices = [];
  102955. this.triangles = [];
  102956. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  102957. var indices = this._mesh.getIndices();
  102958. var submesh = this._mesh.subMeshes[submeshIndex];
  102959. var findInVertices = function (positionToSearch) {
  102960. if (optimizeMesh) {
  102961. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  102962. if (_this.vertices[ii].position.equals(positionToSearch)) {
  102963. return _this.vertices[ii];
  102964. }
  102965. }
  102966. }
  102967. return null;
  102968. };
  102969. var vertexReferences = [];
  102970. var vertexInit = function (i) {
  102971. if (!positionData) {
  102972. return;
  102973. }
  102974. var offset = i + submesh.verticesStart;
  102975. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  102976. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  102977. vertex.originalOffsets.push(offset);
  102978. if (vertex.id === _this.vertices.length) {
  102979. _this.vertices.push(vertex);
  102980. }
  102981. vertexReferences.push(vertex.id);
  102982. };
  102983. //var totalVertices = mesh.getTotalVertices();
  102984. var totalVertices = submesh.verticesCount;
  102985. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  102986. var indicesInit = function (i) {
  102987. if (!indices) {
  102988. return;
  102989. }
  102990. var offset = (submesh.indexStart / 3) + i;
  102991. var pos = (offset * 3);
  102992. var i0 = indices[pos + 0];
  102993. var i1 = indices[pos + 1];
  102994. var i2 = indices[pos + 2];
  102995. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  102996. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  102997. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  102998. var triangle = new DecimationTriangle([v0, v1, v2]);
  102999. triangle.originalOffset = pos;
  103000. _this.triangles.push(triangle);
  103001. };
  103002. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  103003. _this.init(callback);
  103004. });
  103005. });
  103006. };
  103007. QuadraticErrorSimplification.prototype.init = function (callback) {
  103008. var _this = this;
  103009. var triangleInit1 = function (i) {
  103010. var t = _this.triangles[i];
  103011. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  103012. for (var j = 0; j < 3; j++) {
  103013. 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))));
  103014. }
  103015. };
  103016. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  103017. var triangleInit2 = function (i) {
  103018. var t = _this.triangles[i];
  103019. for (var j = 0; j < 3; ++j) {
  103020. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  103021. }
  103022. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103023. };
  103024. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  103025. callback();
  103026. });
  103027. });
  103028. };
  103029. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  103030. var newTriangles = [];
  103031. var i;
  103032. for (i = 0; i < this.vertices.length; ++i) {
  103033. this.vertices[i].triangleCount = 0;
  103034. }
  103035. var t;
  103036. var j;
  103037. for (i = 0; i < this.triangles.length; ++i) {
  103038. if (!this.triangles[i].deleted) {
  103039. t = this.triangles[i];
  103040. for (j = 0; j < 3; ++j) {
  103041. t.vertices[j].triangleCount = 1;
  103042. }
  103043. newTriangles.push(t);
  103044. }
  103045. }
  103046. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  103047. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  103048. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  103049. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  103050. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  103051. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  103052. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  103053. var vertexCount = 0;
  103054. for (i = 0; i < this.vertices.length; ++i) {
  103055. var vertex = this.vertices[i];
  103056. vertex.id = vertexCount;
  103057. if (vertex.triangleCount) {
  103058. vertex.originalOffsets.forEach(function (originalOffset) {
  103059. if (!normalData) {
  103060. return;
  103061. }
  103062. newPositionData.push(vertex.position.x);
  103063. newPositionData.push(vertex.position.y);
  103064. newPositionData.push(vertex.position.z);
  103065. newNormalData.push(normalData[originalOffset * 3]);
  103066. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  103067. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  103068. if (uvs && uvs.length) {
  103069. newUVsData.push(uvs[(originalOffset * 2)]);
  103070. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  103071. }
  103072. else if (colorsData && colorsData.length) {
  103073. newColorsData.push(colorsData[(originalOffset * 4)]);
  103074. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  103075. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  103076. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  103077. }
  103078. ++vertexCount;
  103079. });
  103080. }
  103081. }
  103082. var startingIndex = this._reconstructedMesh.getTotalIndices();
  103083. var startingVertex = this._reconstructedMesh.getTotalVertices();
  103084. var submeshesArray = this._reconstructedMesh.subMeshes;
  103085. this._reconstructedMesh.subMeshes = [];
  103086. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  103087. var originalIndices = this._mesh.getIndices();
  103088. for (i = 0; i < newTriangles.length; ++i) {
  103089. t = newTriangles[i]; //now get the new referencing point for each vertex
  103090. [0, 1, 2].forEach(function (idx) {
  103091. var id = originalIndices[t.originalOffset + idx];
  103092. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  103093. if (offset < 0)
  103094. offset = 0;
  103095. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  103096. });
  103097. }
  103098. //overwriting the old vertex buffers and indices.
  103099. this._reconstructedMesh.setIndices(newIndicesArray);
  103100. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  103101. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  103102. if (newUVsData.length > 0)
  103103. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  103104. if (newColorsData.length > 0)
  103105. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  103106. //create submesh
  103107. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  103108. if (submeshIndex > 0) {
  103109. this._reconstructedMesh.subMeshes = [];
  103110. submeshesArray.forEach(function (submesh) {
  103111. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  103112. });
  103113. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  103114. }
  103115. };
  103116. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  103117. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  103118. this._reconstructedMesh.material = this._mesh.material;
  103119. this._reconstructedMesh.parent = this._mesh.parent;
  103120. this._reconstructedMesh.isVisible = false;
  103121. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  103122. };
  103123. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  103124. for (var i = 0; i < vertex1.triangleCount; ++i) {
  103125. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  103126. if (t.deleted)
  103127. continue;
  103128. var s = this.references[vertex1.triangleStart + i].vertexId;
  103129. var v1 = t.vertices[(s + 1) % 3];
  103130. var v2 = t.vertices[(s + 2) % 3];
  103131. if ((v1 === vertex2 || v2 === vertex2)) {
  103132. deletedArray[i] = true;
  103133. delTr.push(t);
  103134. continue;
  103135. }
  103136. var d1 = v1.position.subtract(point);
  103137. d1 = d1.normalize();
  103138. var d2 = v2.position.subtract(point);
  103139. d2 = d2.normalize();
  103140. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  103141. return true;
  103142. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  103143. deletedArray[i] = false;
  103144. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  103145. return true;
  103146. }
  103147. return false;
  103148. };
  103149. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  103150. var newDeleted = deletedTriangles;
  103151. for (var i = 0; i < vertex.triangleCount; ++i) {
  103152. var ref = this.references[vertex.triangleStart + i];
  103153. var t = this.triangles[ref.triangleId];
  103154. if (t.deleted)
  103155. continue;
  103156. if (deletedArray[i] && t.deletePending) {
  103157. t.deleted = true;
  103158. newDeleted++;
  103159. continue;
  103160. }
  103161. t.vertices[ref.vertexId] = origVertex;
  103162. t.isDirty = true;
  103163. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  103164. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  103165. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  103166. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  103167. this.references.push(ref);
  103168. }
  103169. return newDeleted;
  103170. };
  103171. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  103172. for (var i = 0; i < this.vertices.length; ++i) {
  103173. var vCount = [];
  103174. var vId = [];
  103175. var v = this.vertices[i];
  103176. var j;
  103177. for (j = 0; j < v.triangleCount; ++j) {
  103178. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  103179. for (var ii = 0; ii < 3; ii++) {
  103180. var ofs = 0;
  103181. var vv = triangle.vertices[ii];
  103182. while (ofs < vCount.length) {
  103183. if (vId[ofs] === vv.id)
  103184. break;
  103185. ++ofs;
  103186. }
  103187. if (ofs === vCount.length) {
  103188. vCount.push(1);
  103189. vId.push(vv.id);
  103190. }
  103191. else {
  103192. vCount[ofs]++;
  103193. }
  103194. }
  103195. }
  103196. for (j = 0; j < vCount.length; ++j) {
  103197. if (vCount[j] === 1) {
  103198. this.vertices[vId[j]].isBorder = true;
  103199. }
  103200. else {
  103201. this.vertices[vId[j]].isBorder = false;
  103202. }
  103203. }
  103204. }
  103205. };
  103206. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  103207. if (identifyBorders === void 0) { identifyBorders = false; }
  103208. var i;
  103209. if (!identifyBorders) {
  103210. var newTrianglesVector = [];
  103211. for (i = 0; i < this.triangles.length; ++i) {
  103212. if (!this.triangles[i].deleted) {
  103213. newTrianglesVector.push(this.triangles[i]);
  103214. }
  103215. }
  103216. this.triangles = newTrianglesVector;
  103217. }
  103218. for (i = 0; i < this.vertices.length; ++i) {
  103219. this.vertices[i].triangleCount = 0;
  103220. this.vertices[i].triangleStart = 0;
  103221. }
  103222. var t;
  103223. var j;
  103224. var v;
  103225. for (i = 0; i < this.triangles.length; ++i) {
  103226. t = this.triangles[i];
  103227. for (j = 0; j < 3; ++j) {
  103228. v = t.vertices[j];
  103229. v.triangleCount++;
  103230. }
  103231. }
  103232. var tStart = 0;
  103233. for (i = 0; i < this.vertices.length; ++i) {
  103234. this.vertices[i].triangleStart = tStart;
  103235. tStart += this.vertices[i].triangleCount;
  103236. this.vertices[i].triangleCount = 0;
  103237. }
  103238. var newReferences = new Array(this.triangles.length * 3);
  103239. for (i = 0; i < this.triangles.length; ++i) {
  103240. t = this.triangles[i];
  103241. for (j = 0; j < 3; ++j) {
  103242. v = t.vertices[j];
  103243. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  103244. v.triangleCount++;
  103245. }
  103246. }
  103247. this.references = newReferences;
  103248. if (identifyBorders) {
  103249. this.identifyBorder();
  103250. }
  103251. };
  103252. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  103253. var x = point.x;
  103254. var y = point.y;
  103255. var z = point.z;
  103256. 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
  103257. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  103258. };
  103259. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  103260. var q = vertex1.q.add(vertex2.q);
  103261. var border = vertex1.isBorder && vertex2.isBorder;
  103262. var error = 0;
  103263. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  103264. if (qDet !== 0 && !border) {
  103265. if (!pointResult) {
  103266. pointResult = BABYLON.Vector3.Zero();
  103267. }
  103268. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  103269. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  103270. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  103271. error = this.vertexError(q, pointResult);
  103272. }
  103273. else {
  103274. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  103275. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  103276. var error1 = this.vertexError(q, vertex1.position);
  103277. var error2 = this.vertexError(q, vertex2.position);
  103278. var error3 = this.vertexError(q, p3);
  103279. error = Math.min(error1, error2, error3);
  103280. if (error === error1) {
  103281. if (pointResult) {
  103282. pointResult.copyFrom(vertex1.position);
  103283. }
  103284. }
  103285. else if (error === error2) {
  103286. if (pointResult) {
  103287. pointResult.copyFrom(vertex2.position);
  103288. }
  103289. }
  103290. else {
  103291. if (pointResult) {
  103292. pointResult.copyFrom(p3);
  103293. }
  103294. }
  103295. }
  103296. return error;
  103297. };
  103298. return QuadraticErrorSimplification;
  103299. }());
  103300. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  103301. })(BABYLON || (BABYLON = {}));
  103302. //# sourceMappingURL=babylon.meshSimplification.js.map
  103303. var BABYLON;
  103304. (function (BABYLON) {
  103305. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  103306. get: function () {
  103307. if (!this._simplificationQueue) {
  103308. this._simplificationQueue = new BABYLON.SimplificationQueue();
  103309. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  103310. if (!component) {
  103311. component = new SimplicationQueueSceneComponent(this);
  103312. this._addComponent(component);
  103313. }
  103314. }
  103315. return this._simplificationQueue;
  103316. },
  103317. set: function (value) {
  103318. this._simplificationQueue = value;
  103319. },
  103320. enumerable: true,
  103321. configurable: true
  103322. });
  103323. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  103324. if (parallelProcessing === void 0) { parallelProcessing = true; }
  103325. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  103326. this.getScene().simplificationQueue.addTask({
  103327. settings: settings,
  103328. parallelProcessing: parallelProcessing,
  103329. mesh: this,
  103330. simplificationType: simplificationType,
  103331. successCallback: successCallback
  103332. });
  103333. return this;
  103334. };
  103335. /**
  103336. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  103337. * created in a scene
  103338. */
  103339. var SimplicationQueueSceneComponent = /** @class */ (function () {
  103340. /**
  103341. * Creates a new instance of the component for the given scene
  103342. * @param scene Defines the scene to register the component in
  103343. */
  103344. function SimplicationQueueSceneComponent(scene) {
  103345. /**
  103346. * The component name helpfull to identify the component in the list of scene components.
  103347. */
  103348. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  103349. this.scene = scene;
  103350. }
  103351. /**
  103352. * Registers the component in a given scene
  103353. */
  103354. SimplicationQueueSceneComponent.prototype.register = function () {
  103355. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  103356. };
  103357. /**
  103358. * Rebuilds the elements related to this component in case of
  103359. * context lost for instance.
  103360. */
  103361. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  103362. // Nothing to do for this component
  103363. };
  103364. /**
  103365. * Disposes the component and the associated ressources
  103366. */
  103367. SimplicationQueueSceneComponent.prototype.dispose = function () {
  103368. // Nothing to do for this component
  103369. };
  103370. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  103371. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  103372. this.scene._simplificationQueue.executeNext();
  103373. }
  103374. };
  103375. return SimplicationQueueSceneComponent;
  103376. }());
  103377. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  103378. })(BABYLON || (BABYLON = {}));
  103379. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  103380. var BABYLON;
  103381. (function (BABYLON) {
  103382. /**
  103383. * Class used to represent a specific level of detail of a mesh
  103384. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  103385. */
  103386. var MeshLODLevel = /** @class */ (function () {
  103387. /**
  103388. * Creates a new LOD level
  103389. * @param distance defines the distance where this level should star being displayed
  103390. * @param mesh defines the mesh to use to render this level
  103391. */
  103392. function MeshLODLevel(
  103393. /** Defines the distance where this level should star being displayed */
  103394. distance,
  103395. /** Defines the mesh to use to render this level */
  103396. mesh) {
  103397. this.distance = distance;
  103398. this.mesh = mesh;
  103399. }
  103400. return MeshLODLevel;
  103401. }());
  103402. BABYLON.MeshLODLevel = MeshLODLevel;
  103403. })(BABYLON || (BABYLON = {}));
  103404. //# sourceMappingURL=babylon.meshLODLevel.js.map
  103405. var BABYLON;
  103406. (function (BABYLON) {
  103407. /**
  103408. * Defines the root class used to create scene optimization to use with SceneOptimizer
  103409. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103410. */
  103411. var SceneOptimization = /** @class */ (function () {
  103412. /**
  103413. * Creates the SceneOptimization object
  103414. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103415. * @param desc defines the description associated with the optimization
  103416. */
  103417. function SceneOptimization(
  103418. /**
  103419. * Defines the priority of this optimization (0 by default which means first in the list)
  103420. */
  103421. priority) {
  103422. if (priority === void 0) { priority = 0; }
  103423. this.priority = priority;
  103424. }
  103425. /**
  103426. * Gets a string describing the action executed by the current optimization
  103427. * @returns description string
  103428. */
  103429. SceneOptimization.prototype.getDescription = function () {
  103430. return "";
  103431. };
  103432. /**
  103433. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103434. * @param scene defines the current scene where to apply this optimization
  103435. * @param optimizer defines the current optimizer
  103436. * @returns true if everything that can be done was applied
  103437. */
  103438. SceneOptimization.prototype.apply = function (scene, optimizer) {
  103439. return true;
  103440. };
  103441. ;
  103442. return SceneOptimization;
  103443. }());
  103444. BABYLON.SceneOptimization = SceneOptimization;
  103445. /**
  103446. * Defines an optimization used to reduce the size of render target textures
  103447. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103448. */
  103449. var TextureOptimization = /** @class */ (function (_super) {
  103450. __extends(TextureOptimization, _super);
  103451. /**
  103452. * Creates the TextureOptimization object
  103453. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103454. * @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
  103455. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103456. */
  103457. function TextureOptimization(
  103458. /**
  103459. * Defines the priority of this optimization (0 by default which means first in the list)
  103460. */
  103461. priority,
  103462. /**
  103463. * 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
  103464. */
  103465. maximumSize,
  103466. /**
  103467. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  103468. */
  103469. step) {
  103470. if (priority === void 0) { priority = 0; }
  103471. if (maximumSize === void 0) { maximumSize = 1024; }
  103472. if (step === void 0) { step = 0.5; }
  103473. var _this = _super.call(this, priority) || this;
  103474. _this.priority = priority;
  103475. _this.maximumSize = maximumSize;
  103476. _this.step = step;
  103477. return _this;
  103478. }
  103479. /**
  103480. * Gets a string describing the action executed by the current optimization
  103481. * @returns description string
  103482. */
  103483. TextureOptimization.prototype.getDescription = function () {
  103484. return "Reducing render target texture size to " + this.maximumSize;
  103485. };
  103486. /**
  103487. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103488. * @param scene defines the current scene where to apply this optimization
  103489. * @param optimizer defines the current optimizer
  103490. * @returns true if everything that can be done was applied
  103491. */
  103492. TextureOptimization.prototype.apply = function (scene, optimizer) {
  103493. var allDone = true;
  103494. for (var index = 0; index < scene.textures.length; index++) {
  103495. var texture = scene.textures[index];
  103496. if (!texture.canRescale || texture.getContext) {
  103497. continue;
  103498. }
  103499. var currentSize = texture.getSize();
  103500. var maxDimension = Math.max(currentSize.width, currentSize.height);
  103501. if (maxDimension > this.maximumSize) {
  103502. texture.scale(this.step);
  103503. allDone = false;
  103504. }
  103505. }
  103506. return allDone;
  103507. };
  103508. return TextureOptimization;
  103509. }(SceneOptimization));
  103510. BABYLON.TextureOptimization = TextureOptimization;
  103511. /**
  103512. * Defines an optimization used to increase or decrease the rendering resolution
  103513. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103514. */
  103515. var HardwareScalingOptimization = /** @class */ (function (_super) {
  103516. __extends(HardwareScalingOptimization, _super);
  103517. /**
  103518. * Creates the HardwareScalingOptimization object
  103519. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103520. * @param maximumScale defines the maximum scale to use (2 by default)
  103521. * @param step defines the step to use between two passes (0.5 by default)
  103522. */
  103523. function HardwareScalingOptimization(
  103524. /**
  103525. * Defines the priority of this optimization (0 by default which means first in the list)
  103526. */
  103527. priority,
  103528. /**
  103529. * Defines the maximum scale to use (2 by default)
  103530. */
  103531. maximumScale,
  103532. /**
  103533. * Defines the step to use between two passes (0.5 by default)
  103534. */
  103535. step) {
  103536. if (priority === void 0) { priority = 0; }
  103537. if (maximumScale === void 0) { maximumScale = 2; }
  103538. if (step === void 0) { step = 0.25; }
  103539. var _this = _super.call(this, priority) || this;
  103540. _this.priority = priority;
  103541. _this.maximumScale = maximumScale;
  103542. _this.step = step;
  103543. _this._currentScale = -1;
  103544. _this._directionOffset = 1;
  103545. return _this;
  103546. }
  103547. /**
  103548. * Gets a string describing the action executed by the current optimization
  103549. * @return description string
  103550. */
  103551. HardwareScalingOptimization.prototype.getDescription = function () {
  103552. return "Setting hardware scaling level to " + this._currentScale;
  103553. };
  103554. /**
  103555. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103556. * @param scene defines the current scene where to apply this optimization
  103557. * @param optimizer defines the current optimizer
  103558. * @returns true if everything that can be done was applied
  103559. */
  103560. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  103561. if (this._currentScale === -1) {
  103562. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  103563. if (this._currentScale > this.maximumScale) {
  103564. this._directionOffset = -1;
  103565. }
  103566. }
  103567. this._currentScale += this._directionOffset * this.step;
  103568. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  103569. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  103570. };
  103571. ;
  103572. return HardwareScalingOptimization;
  103573. }(SceneOptimization));
  103574. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  103575. /**
  103576. * Defines an optimization used to remove shadows
  103577. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103578. */
  103579. var ShadowsOptimization = /** @class */ (function (_super) {
  103580. __extends(ShadowsOptimization, _super);
  103581. function ShadowsOptimization() {
  103582. return _super !== null && _super.apply(this, arguments) || this;
  103583. }
  103584. /**
  103585. * Gets a string describing the action executed by the current optimization
  103586. * @return description string
  103587. */
  103588. ShadowsOptimization.prototype.getDescription = function () {
  103589. return "Turning shadows on/off";
  103590. };
  103591. /**
  103592. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103593. * @param scene defines the current scene where to apply this optimization
  103594. * @param optimizer defines the current optimizer
  103595. * @returns true if everything that can be done was applied
  103596. */
  103597. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  103598. scene.shadowsEnabled = optimizer.isInImprovementMode;
  103599. return true;
  103600. };
  103601. ;
  103602. return ShadowsOptimization;
  103603. }(SceneOptimization));
  103604. BABYLON.ShadowsOptimization = ShadowsOptimization;
  103605. /**
  103606. * Defines an optimization used to turn post-processes off
  103607. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103608. */
  103609. var PostProcessesOptimization = /** @class */ (function (_super) {
  103610. __extends(PostProcessesOptimization, _super);
  103611. function PostProcessesOptimization() {
  103612. return _super !== null && _super.apply(this, arguments) || this;
  103613. }
  103614. /**
  103615. * Gets a string describing the action executed by the current optimization
  103616. * @return description string
  103617. */
  103618. PostProcessesOptimization.prototype.getDescription = function () {
  103619. return "Turning post-processes on/off";
  103620. };
  103621. /**
  103622. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103623. * @param scene defines the current scene where to apply this optimization
  103624. * @param optimizer defines the current optimizer
  103625. * @returns true if everything that can be done was applied
  103626. */
  103627. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  103628. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  103629. return true;
  103630. };
  103631. ;
  103632. return PostProcessesOptimization;
  103633. }(SceneOptimization));
  103634. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  103635. /**
  103636. * Defines an optimization used to turn lens flares off
  103637. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103638. */
  103639. var LensFlaresOptimization = /** @class */ (function (_super) {
  103640. __extends(LensFlaresOptimization, _super);
  103641. function LensFlaresOptimization() {
  103642. return _super !== null && _super.apply(this, arguments) || this;
  103643. }
  103644. /**
  103645. * Gets a string describing the action executed by the current optimization
  103646. * @return description string
  103647. */
  103648. LensFlaresOptimization.prototype.getDescription = function () {
  103649. return "Turning lens flares on/off";
  103650. };
  103651. /**
  103652. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103653. * @param scene defines the current scene where to apply this optimization
  103654. * @param optimizer defines the current optimizer
  103655. * @returns true if everything that can be done was applied
  103656. */
  103657. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  103658. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  103659. return true;
  103660. };
  103661. ;
  103662. return LensFlaresOptimization;
  103663. }(SceneOptimization));
  103664. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  103665. /**
  103666. * Defines an optimization based on user defined callback.
  103667. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103668. */
  103669. var CustomOptimization = /** @class */ (function (_super) {
  103670. __extends(CustomOptimization, _super);
  103671. function CustomOptimization() {
  103672. return _super !== null && _super.apply(this, arguments) || this;
  103673. }
  103674. /**
  103675. * Gets a string describing the action executed by the current optimization
  103676. * @returns description string
  103677. */
  103678. CustomOptimization.prototype.getDescription = function () {
  103679. if (this.onGetDescription) {
  103680. return this.onGetDescription();
  103681. }
  103682. return "Running user defined callback";
  103683. };
  103684. /**
  103685. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103686. * @param scene defines the current scene where to apply this optimization
  103687. * @param optimizer defines the current optimizer
  103688. * @returns true if everything that can be done was applied
  103689. */
  103690. CustomOptimization.prototype.apply = function (scene, optimizer) {
  103691. if (this.onApply) {
  103692. return this.onApply(scene, optimizer);
  103693. }
  103694. return true;
  103695. };
  103696. ;
  103697. return CustomOptimization;
  103698. }(SceneOptimization));
  103699. BABYLON.CustomOptimization = CustomOptimization;
  103700. /**
  103701. * Defines an optimization used to turn particles off
  103702. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103703. */
  103704. var ParticlesOptimization = /** @class */ (function (_super) {
  103705. __extends(ParticlesOptimization, _super);
  103706. function ParticlesOptimization() {
  103707. return _super !== null && _super.apply(this, arguments) || this;
  103708. }
  103709. /**
  103710. * Gets a string describing the action executed by the current optimization
  103711. * @return description string
  103712. */
  103713. ParticlesOptimization.prototype.getDescription = function () {
  103714. return "Turning particles on/off";
  103715. };
  103716. /**
  103717. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103718. * @param scene defines the current scene where to apply this optimization
  103719. * @param optimizer defines the current optimizer
  103720. * @returns true if everything that can be done was applied
  103721. */
  103722. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  103723. scene.particlesEnabled = optimizer.isInImprovementMode;
  103724. return true;
  103725. };
  103726. ;
  103727. return ParticlesOptimization;
  103728. }(SceneOptimization));
  103729. BABYLON.ParticlesOptimization = ParticlesOptimization;
  103730. /**
  103731. * Defines an optimization used to turn render targets off
  103732. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103733. */
  103734. var RenderTargetsOptimization = /** @class */ (function (_super) {
  103735. __extends(RenderTargetsOptimization, _super);
  103736. function RenderTargetsOptimization() {
  103737. return _super !== null && _super.apply(this, arguments) || this;
  103738. }
  103739. /**
  103740. * Gets a string describing the action executed by the current optimization
  103741. * @return description string
  103742. */
  103743. RenderTargetsOptimization.prototype.getDescription = function () {
  103744. return "Turning render targets off";
  103745. };
  103746. /**
  103747. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103748. * @param scene defines the current scene where to apply this optimization
  103749. * @param optimizer defines the current optimizer
  103750. * @returns true if everything that can be done was applied
  103751. */
  103752. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  103753. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  103754. return true;
  103755. };
  103756. ;
  103757. return RenderTargetsOptimization;
  103758. }(SceneOptimization));
  103759. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  103760. /**
  103761. * Defines an optimization used to merge meshes with compatible materials
  103762. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103763. */
  103764. var MergeMeshesOptimization = /** @class */ (function (_super) {
  103765. __extends(MergeMeshesOptimization, _super);
  103766. function MergeMeshesOptimization() {
  103767. var _this = _super !== null && _super.apply(this, arguments) || this;
  103768. _this._canBeMerged = function (abstractMesh) {
  103769. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  103770. return false;
  103771. }
  103772. var mesh = abstractMesh;
  103773. if (mesh.isDisposed()) {
  103774. return false;
  103775. }
  103776. if (!mesh.isVisible || !mesh.isEnabled()) {
  103777. return false;
  103778. }
  103779. if (mesh.instances.length > 0) {
  103780. return false;
  103781. }
  103782. if (mesh.skeleton || mesh.hasLODLevels) {
  103783. return false;
  103784. }
  103785. return true;
  103786. };
  103787. return _this;
  103788. }
  103789. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  103790. /**
  103791. * Gets or sets a boolean which defines if optimization octree has to be updated
  103792. */
  103793. get: function () {
  103794. return MergeMeshesOptimization._UpdateSelectionTree;
  103795. },
  103796. /**
  103797. * Gets or sets a boolean which defines if optimization octree has to be updated
  103798. */
  103799. set: function (value) {
  103800. MergeMeshesOptimization._UpdateSelectionTree = value;
  103801. },
  103802. enumerable: true,
  103803. configurable: true
  103804. });
  103805. /**
  103806. * Gets a string describing the action executed by the current optimization
  103807. * @return description string
  103808. */
  103809. MergeMeshesOptimization.prototype.getDescription = function () {
  103810. return "Merging similar meshes together";
  103811. };
  103812. /**
  103813. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  103814. * @param scene defines the current scene where to apply this optimization
  103815. * @param optimizer defines the current optimizer
  103816. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  103817. * @returns true if everything that can be done was applied
  103818. */
  103819. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  103820. var globalPool = scene.meshes.slice(0);
  103821. var globalLength = globalPool.length;
  103822. for (var index = 0; index < globalLength; index++) {
  103823. var currentPool = new Array();
  103824. var current = globalPool[index];
  103825. // Checks
  103826. if (!this._canBeMerged(current)) {
  103827. continue;
  103828. }
  103829. currentPool.push(current);
  103830. // Find compatible meshes
  103831. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  103832. var otherMesh = globalPool[subIndex];
  103833. if (!this._canBeMerged(otherMesh)) {
  103834. continue;
  103835. }
  103836. if (otherMesh.material !== current.material) {
  103837. continue;
  103838. }
  103839. if (otherMesh.checkCollisions !== current.checkCollisions) {
  103840. continue;
  103841. }
  103842. currentPool.push(otherMesh);
  103843. globalLength--;
  103844. globalPool.splice(subIndex, 1);
  103845. subIndex--;
  103846. }
  103847. if (currentPool.length < 2) {
  103848. continue;
  103849. }
  103850. // Merge meshes
  103851. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  103852. }
  103853. // Call the octree system optimization if it is defined.
  103854. var sceneAsAny = scene;
  103855. if (sceneAsAny.createOrUpdateSelectionOctree) {
  103856. if (updateSelectionTree != undefined) {
  103857. if (updateSelectionTree) {
  103858. sceneAsAny.createOrUpdateSelectionOctree();
  103859. }
  103860. }
  103861. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  103862. sceneAsAny.createOrUpdateSelectionOctree();
  103863. }
  103864. }
  103865. return true;
  103866. };
  103867. ;
  103868. MergeMeshesOptimization._UpdateSelectionTree = false;
  103869. return MergeMeshesOptimization;
  103870. }(SceneOptimization));
  103871. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  103872. /**
  103873. * Defines a list of options used by SceneOptimizer
  103874. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  103875. */
  103876. var SceneOptimizerOptions = /** @class */ (function () {
  103877. /**
  103878. * Creates a new list of options used by SceneOptimizer
  103879. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  103880. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  103881. */
  103882. function SceneOptimizerOptions(
  103883. /**
  103884. * Defines the target frame rate to reach (60 by default)
  103885. */
  103886. targetFrameRate,
  103887. /**
  103888. * Defines the interval between two checkes (2000ms by default)
  103889. */
  103890. trackerDuration) {
  103891. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  103892. if (trackerDuration === void 0) { trackerDuration = 2000; }
  103893. this.targetFrameRate = targetFrameRate;
  103894. this.trackerDuration = trackerDuration;
  103895. /**
  103896. * Gets the list of optimizations to apply
  103897. */
  103898. this.optimizations = new Array();
  103899. }
  103900. /**
  103901. * Add a new optimization
  103902. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  103903. * @returns the current SceneOptimizerOptions
  103904. */
  103905. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  103906. this.optimizations.push(optimization);
  103907. return this;
  103908. };
  103909. /**
  103910. * Add a new custom optimization
  103911. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  103912. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  103913. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  103914. * @returns the current SceneOptimizerOptions
  103915. */
  103916. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  103917. if (priority === void 0) { priority = 0; }
  103918. var optimization = new CustomOptimization(priority);
  103919. optimization.onApply = onApply;
  103920. optimization.onGetDescription = onGetDescription;
  103921. this.optimizations.push(optimization);
  103922. return this;
  103923. };
  103924. /**
  103925. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  103926. * @param targetFrameRate defines the target frame rate (60 by default)
  103927. * @returns a SceneOptimizerOptions object
  103928. */
  103929. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  103930. var result = new SceneOptimizerOptions(targetFrameRate);
  103931. var priority = 0;
  103932. result.addOptimization(new MergeMeshesOptimization(priority));
  103933. result.addOptimization(new ShadowsOptimization(priority));
  103934. result.addOptimization(new LensFlaresOptimization(priority));
  103935. // Next priority
  103936. priority++;
  103937. result.addOptimization(new PostProcessesOptimization(priority));
  103938. result.addOptimization(new ParticlesOptimization(priority));
  103939. // Next priority
  103940. priority++;
  103941. result.addOptimization(new TextureOptimization(priority, 1024));
  103942. return result;
  103943. };
  103944. /**
  103945. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  103946. * @param targetFrameRate defines the target frame rate (60 by default)
  103947. * @returns a SceneOptimizerOptions object
  103948. */
  103949. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  103950. var result = new SceneOptimizerOptions(targetFrameRate);
  103951. var priority = 0;
  103952. result.addOptimization(new MergeMeshesOptimization(priority));
  103953. result.addOptimization(new ShadowsOptimization(priority));
  103954. result.addOptimization(new LensFlaresOptimization(priority));
  103955. // Next priority
  103956. priority++;
  103957. result.addOptimization(new PostProcessesOptimization(priority));
  103958. result.addOptimization(new ParticlesOptimization(priority));
  103959. // Next priority
  103960. priority++;
  103961. result.addOptimization(new TextureOptimization(priority, 512));
  103962. // Next priority
  103963. priority++;
  103964. result.addOptimization(new RenderTargetsOptimization(priority));
  103965. // Next priority
  103966. priority++;
  103967. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  103968. return result;
  103969. };
  103970. /**
  103971. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  103972. * @param targetFrameRate defines the target frame rate (60 by default)
  103973. * @returns a SceneOptimizerOptions object
  103974. */
  103975. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  103976. var result = new SceneOptimizerOptions(targetFrameRate);
  103977. var priority = 0;
  103978. result.addOptimization(new MergeMeshesOptimization(priority));
  103979. result.addOptimization(new ShadowsOptimization(priority));
  103980. result.addOptimization(new LensFlaresOptimization(priority));
  103981. // Next priority
  103982. priority++;
  103983. result.addOptimization(new PostProcessesOptimization(priority));
  103984. result.addOptimization(new ParticlesOptimization(priority));
  103985. // Next priority
  103986. priority++;
  103987. result.addOptimization(new TextureOptimization(priority, 256));
  103988. // Next priority
  103989. priority++;
  103990. result.addOptimization(new RenderTargetsOptimization(priority));
  103991. // Next priority
  103992. priority++;
  103993. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  103994. return result;
  103995. };
  103996. return SceneOptimizerOptions;
  103997. }());
  103998. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  103999. /**
  104000. * Class used to run optimizations in order to reach a target frame rate
  104001. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  104002. */
  104003. var SceneOptimizer = /** @class */ (function () {
  104004. /**
  104005. * Creates a new SceneOptimizer
  104006. * @param scene defines the scene to work on
  104007. * @param options defines the options to use with the SceneOptimizer
  104008. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  104009. * @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)
  104010. */
  104011. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  104012. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  104013. if (improvementMode === void 0) { improvementMode = false; }
  104014. var _this = this;
  104015. this._isRunning = false;
  104016. this._currentPriorityLevel = 0;
  104017. this._targetFrameRate = 60;
  104018. this._trackerDuration = 2000;
  104019. this._currentFrameRate = 0;
  104020. this._improvementMode = false;
  104021. /**
  104022. * Defines an observable called when the optimizer reaches the target frame rate
  104023. */
  104024. this.onSuccessObservable = new BABYLON.Observable();
  104025. /**
  104026. * Defines an observable called when the optimizer enables an optimization
  104027. */
  104028. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  104029. /**
  104030. * Defines an observable called when the optimizer is not able to reach the target frame rate
  104031. */
  104032. this.onFailureObservable = new BABYLON.Observable();
  104033. if (!options) {
  104034. this._options = new SceneOptimizerOptions();
  104035. }
  104036. else {
  104037. this._options = options;
  104038. }
  104039. if (this._options.targetFrameRate) {
  104040. this._targetFrameRate = this._options.targetFrameRate;
  104041. }
  104042. if (this._options.trackerDuration) {
  104043. this._trackerDuration = this._options.trackerDuration;
  104044. }
  104045. if (autoGeneratePriorities) {
  104046. var priority = 0;
  104047. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  104048. var optim = _a[_i];
  104049. optim.priority = priority++;
  104050. }
  104051. }
  104052. this._improvementMode = improvementMode;
  104053. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104054. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  104055. _this._sceneDisposeObserver = null;
  104056. _this.dispose();
  104057. });
  104058. }
  104059. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  104060. /**
  104061. * Gets a boolean indicating if the optimizer is in improvement mode
  104062. */
  104063. get: function () {
  104064. return this._improvementMode;
  104065. },
  104066. enumerable: true,
  104067. configurable: true
  104068. });
  104069. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  104070. /**
  104071. * Gets the current priority level (0 at start)
  104072. */
  104073. get: function () {
  104074. return this._currentPriorityLevel;
  104075. },
  104076. enumerable: true,
  104077. configurable: true
  104078. });
  104079. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  104080. /**
  104081. * Gets the current frame rate checked by the SceneOptimizer
  104082. */
  104083. get: function () {
  104084. return this._currentFrameRate;
  104085. },
  104086. enumerable: true,
  104087. configurable: true
  104088. });
  104089. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  104090. /**
  104091. * Gets or sets the current target frame rate (60 by default)
  104092. */
  104093. get: function () {
  104094. return this._targetFrameRate;
  104095. },
  104096. /**
  104097. * Gets or sets the current target frame rate (60 by default)
  104098. */
  104099. set: function (value) {
  104100. this._targetFrameRate = value;
  104101. },
  104102. enumerable: true,
  104103. configurable: true
  104104. });
  104105. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  104106. /**
  104107. * Gets or sets the current interval between two checks (every 2000ms by default)
  104108. */
  104109. get: function () {
  104110. return this._trackerDuration;
  104111. },
  104112. /**
  104113. * Gets or sets the current interval between two checks (every 2000ms by default)
  104114. */
  104115. set: function (value) {
  104116. this._trackerDuration = value;
  104117. },
  104118. enumerable: true,
  104119. configurable: true
  104120. });
  104121. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  104122. /**
  104123. * Gets the list of active optimizations
  104124. */
  104125. get: function () {
  104126. return this._options.optimizations;
  104127. },
  104128. enumerable: true,
  104129. configurable: true
  104130. });
  104131. /**
  104132. * Stops the current optimizer
  104133. */
  104134. SceneOptimizer.prototype.stop = function () {
  104135. this._isRunning = false;
  104136. };
  104137. /**
  104138. * Reset the optimizer to initial step (current priority level = 0)
  104139. */
  104140. SceneOptimizer.prototype.reset = function () {
  104141. this._currentPriorityLevel = 0;
  104142. };
  104143. /**
  104144. * Start the optimizer. By default it will try to reach a specific framerate
  104145. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  104146. */
  104147. SceneOptimizer.prototype.start = function () {
  104148. var _this = this;
  104149. if (this._isRunning) {
  104150. return;
  104151. }
  104152. this._isRunning = true;
  104153. // Let's wait for the scene to be ready before running our check
  104154. this._scene.executeWhenReady(function () {
  104155. setTimeout(function () {
  104156. _this._checkCurrentState();
  104157. }, _this._trackerDuration);
  104158. });
  104159. };
  104160. SceneOptimizer.prototype._checkCurrentState = function () {
  104161. var _this = this;
  104162. if (!this._isRunning) {
  104163. return;
  104164. }
  104165. var scene = this._scene;
  104166. var options = this._options;
  104167. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  104168. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  104169. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  104170. this._isRunning = false;
  104171. this.onSuccessObservable.notifyObservers(this);
  104172. return;
  104173. }
  104174. // Apply current level of optimizations
  104175. var allDone = true;
  104176. var noOptimizationApplied = true;
  104177. for (var index = 0; index < options.optimizations.length; index++) {
  104178. var optimization = options.optimizations[index];
  104179. if (optimization.priority === this._currentPriorityLevel) {
  104180. noOptimizationApplied = false;
  104181. allDone = allDone && optimization.apply(scene, this);
  104182. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  104183. }
  104184. }
  104185. // If no optimization was applied, this is a failure :(
  104186. if (noOptimizationApplied) {
  104187. this._isRunning = false;
  104188. this.onFailureObservable.notifyObservers(this);
  104189. return;
  104190. }
  104191. // If all optimizations were done, move to next level
  104192. if (allDone) {
  104193. this._currentPriorityLevel++;
  104194. }
  104195. // Let's the system running for a specific amount of time before checking FPS
  104196. scene.executeWhenReady(function () {
  104197. setTimeout(function () {
  104198. _this._checkCurrentState();
  104199. }, _this._trackerDuration);
  104200. });
  104201. };
  104202. /**
  104203. * Release all resources
  104204. */
  104205. SceneOptimizer.prototype.dispose = function () {
  104206. this.stop();
  104207. this.onSuccessObservable.clear();
  104208. this.onFailureObservable.clear();
  104209. this.onNewOptimizationAppliedObservable.clear();
  104210. if (this._sceneDisposeObserver) {
  104211. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  104212. }
  104213. };
  104214. /**
  104215. * Helper function to create a SceneOptimizer with one single line of code
  104216. * @param scene defines the scene to work on
  104217. * @param options defines the options to use with the SceneOptimizer
  104218. * @param onSuccess defines a callback to call on success
  104219. * @param onFailure defines a callback to call on failure
  104220. * @returns the new SceneOptimizer object
  104221. */
  104222. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  104223. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  104224. if (onSuccess) {
  104225. optimizer.onSuccessObservable.add(function () {
  104226. onSuccess();
  104227. });
  104228. }
  104229. if (onFailure) {
  104230. optimizer.onFailureObservable.add(function () {
  104231. onFailure();
  104232. });
  104233. }
  104234. optimizer.start();
  104235. return optimizer;
  104236. };
  104237. return SceneOptimizer;
  104238. }());
  104239. BABYLON.SceneOptimizer = SceneOptimizer;
  104240. })(BABYLON || (BABYLON = {}));
  104241. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  104242. var BABYLON;
  104243. (function (BABYLON) {
  104244. /**
  104245. * Gets the outline renderer associated with the scene
  104246. * @returns a OutlineRenderer
  104247. */
  104248. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  104249. if (!this._outlineRenderer) {
  104250. this._outlineRenderer = new OutlineRenderer(this);
  104251. }
  104252. return this._outlineRenderer;
  104253. };
  104254. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  104255. get: function () {
  104256. return this._renderOutline;
  104257. },
  104258. set: function (value) {
  104259. if (value) {
  104260. // Lazy Load the component.
  104261. this.getScene().getOutlineRenderer();
  104262. }
  104263. this._renderOutline = value;
  104264. },
  104265. enumerable: true,
  104266. configurable: true
  104267. });
  104268. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  104269. get: function () {
  104270. return this._renderOverlay;
  104271. },
  104272. set: function (value) {
  104273. if (value) {
  104274. // Lazy Load the component.
  104275. this.getScene().getOutlineRenderer();
  104276. }
  104277. this._renderOverlay = value;
  104278. },
  104279. enumerable: true,
  104280. configurable: true
  104281. });
  104282. /**
  104283. * This class is responsible to draw bothe outline/overlay of meshes.
  104284. * It should not be used directly but through the available method on mesh.
  104285. */
  104286. var OutlineRenderer = /** @class */ (function () {
  104287. /**
  104288. * Instantiates a new outline renderer. (There could be only one per scene).
  104289. * @param scene Defines the scene it belongs to
  104290. */
  104291. function OutlineRenderer(scene) {
  104292. /**
  104293. * The name of the component. Each component must have a unique name.
  104294. */
  104295. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  104296. /**
  104297. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  104298. */
  104299. this.zOffset = 1;
  104300. this.scene = scene;
  104301. this._engine = scene.getEngine();
  104302. this.scene._addComponent(this);
  104303. }
  104304. /**
  104305. * Register the component to one instance of a scene.
  104306. */
  104307. OutlineRenderer.prototype.register = function () {
  104308. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  104309. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  104310. };
  104311. /**
  104312. * Rebuilds the elements related to this component in case of
  104313. * context lost for instance.
  104314. */
  104315. OutlineRenderer.prototype.rebuild = function () {
  104316. // Nothing to do here.
  104317. };
  104318. /**
  104319. * Disposes the component and the associated ressources.
  104320. */
  104321. OutlineRenderer.prototype.dispose = function () {
  104322. // Nothing to do here.
  104323. };
  104324. /**
  104325. * Renders the outline in the canvas.
  104326. * @param subMesh Defines the sumesh to render
  104327. * @param batch Defines the batch of meshes in case of instances
  104328. * @param useOverlay Defines if the rendering is for the overlay or the outline
  104329. */
  104330. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  104331. var _this = this;
  104332. if (useOverlay === void 0) { useOverlay = false; }
  104333. var scene = this.scene;
  104334. var engine = scene.getEngine();
  104335. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104336. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  104337. return;
  104338. }
  104339. var mesh = subMesh.getRenderingMesh();
  104340. var material = subMesh.getMaterial();
  104341. if (!material || !scene.activeCamera) {
  104342. return;
  104343. }
  104344. engine.enableEffect(this._effect);
  104345. // Logarithmic depth
  104346. if (material.useLogarithmicDepth) {
  104347. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  104348. }
  104349. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  104350. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  104351. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  104352. // Bones
  104353. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104354. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104355. }
  104356. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  104357. // Alpha test
  104358. if (material && material.needAlphaTesting()) {
  104359. var alphaTexture = material.getAlphaTestTexture();
  104360. if (alphaTexture) {
  104361. this._effect.setTexture("diffuseSampler", alphaTexture);
  104362. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  104363. }
  104364. }
  104365. engine.setZOffset(-this.zOffset);
  104366. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  104367. engine.setZOffset(0);
  104368. };
  104369. /**
  104370. * Returns whether or not the outline renderer is ready for a given submesh.
  104371. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  104372. * @param subMesh Defines the submesh to check readyness for
  104373. * @param useInstances Defines wheter wee are trying to render instances or not
  104374. * @returns true if ready otherwise false
  104375. */
  104376. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  104377. var defines = [];
  104378. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  104379. var mesh = subMesh.getMesh();
  104380. var material = subMesh.getMaterial();
  104381. if (material) {
  104382. // Alpha test
  104383. if (material.needAlphaTesting()) {
  104384. defines.push("#define ALPHATEST");
  104385. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104386. attribs.push(BABYLON.VertexBuffer.UVKind);
  104387. defines.push("#define UV1");
  104388. }
  104389. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  104390. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104391. defines.push("#define UV2");
  104392. }
  104393. }
  104394. //Logarithmic depth
  104395. if (material.useLogarithmicDepth) {
  104396. defines.push("#define LOGARITHMICDEPTH");
  104397. }
  104398. }
  104399. // Bones
  104400. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104401. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104402. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104403. if (mesh.numBoneInfluencers > 4) {
  104404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104406. }
  104407. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104408. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  104409. }
  104410. else {
  104411. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104412. }
  104413. // Instances
  104414. if (useInstances) {
  104415. defines.push("#define INSTANCES");
  104416. attribs.push("world0");
  104417. attribs.push("world1");
  104418. attribs.push("world2");
  104419. attribs.push("world3");
  104420. }
  104421. // Get correct effect
  104422. var join = defines.join("\n");
  104423. if (this._cachedDefines !== join) {
  104424. this._cachedDefines = join;
  104425. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  104426. }
  104427. return this._effect.isReady();
  104428. };
  104429. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  104430. // Outline - step 1
  104431. this._savedDepthWrite = this._engine.getDepthWrite();
  104432. if (mesh.renderOutline) {
  104433. this._engine.setDepthWrite(false);
  104434. this.render(subMesh, batch);
  104435. this._engine.setDepthWrite(this._savedDepthWrite);
  104436. }
  104437. };
  104438. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  104439. // Outline - step 2
  104440. if (mesh.renderOutline && this._savedDepthWrite) {
  104441. this._engine.setDepthWrite(true);
  104442. this._engine.setColorWrite(false);
  104443. this.render(subMesh, batch);
  104444. this._engine.setColorWrite(true);
  104445. }
  104446. // Overlay
  104447. if (mesh.renderOverlay) {
  104448. var currentMode = this._engine.getAlphaMode();
  104449. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104450. this.render(subMesh, batch, true);
  104451. this._engine.setAlphaMode(currentMode);
  104452. }
  104453. };
  104454. return OutlineRenderer;
  104455. }());
  104456. BABYLON.OutlineRenderer = OutlineRenderer;
  104457. })(BABYLON || (BABYLON = {}));
  104458. //# sourceMappingURL=babylon.outlineRenderer.js.map
  104459. var BABYLON;
  104460. (function (BABYLON) {
  104461. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  104462. if (this._edgesRenderer) {
  104463. this._edgesRenderer.dispose();
  104464. this._edgesRenderer = null;
  104465. }
  104466. return this;
  104467. };
  104468. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104469. if (epsilon === void 0) { epsilon = 0.95; }
  104470. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104471. this.disableEdgesRendering();
  104472. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104473. return this;
  104474. };
  104475. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  104476. get: function () {
  104477. return this._edgesRenderer;
  104478. },
  104479. enumerable: true,
  104480. configurable: true
  104481. });
  104482. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  104483. if (epsilon === void 0) { epsilon = 0.95; }
  104484. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104485. this.disableEdgesRendering();
  104486. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  104487. return this;
  104488. };
  104489. /**
  104490. * FaceAdjacencies Helper class to generate edges
  104491. */
  104492. var FaceAdjacencies = /** @class */ (function () {
  104493. function FaceAdjacencies() {
  104494. this.edges = new Array();
  104495. this.edgesConnectedCount = 0;
  104496. }
  104497. return FaceAdjacencies;
  104498. }());
  104499. /**
  104500. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  104501. */
  104502. var EdgesRenderer = /** @class */ (function () {
  104503. /**
  104504. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  104505. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  104506. * @param source Mesh used to create edges
  104507. * @param epsilon sum of angles in adjacency to check for edge
  104508. * @param checkVerticesInsteadOfIndices
  104509. * @param generateEdgesLines - should generate Lines or only prepare resources.
  104510. */
  104511. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  104512. if (epsilon === void 0) { epsilon = 0.95; }
  104513. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104514. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  104515. var _this = this;
  104516. /**
  104517. * Define the size of the edges with an orthographic camera
  104518. */
  104519. this.edgesWidthScalerForOrthographic = 1000.0;
  104520. /**
  104521. * Define the size of the edges with a perspective camera
  104522. */
  104523. this.edgesWidthScalerForPerspective = 50.0;
  104524. this._linesPositions = new Array();
  104525. this._linesNormals = new Array();
  104526. this._linesIndices = new Array();
  104527. this._buffers = {};
  104528. this._checkVerticesInsteadOfIndices = false;
  104529. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  104530. this.isEnabled = true;
  104531. this._source = source;
  104532. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  104533. this._epsilon = epsilon;
  104534. this._prepareRessources();
  104535. if (generateEdgesLines) {
  104536. this._generateEdgesLines();
  104537. }
  104538. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  104539. _this._rebuild();
  104540. });
  104541. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  104542. _this.dispose();
  104543. });
  104544. }
  104545. EdgesRenderer.prototype._prepareRessources = function () {
  104546. if (this._lineShader) {
  104547. return;
  104548. }
  104549. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  104550. attributes: ["position", "normal"],
  104551. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  104552. });
  104553. this._lineShader.disableDepthWrite = true;
  104554. this._lineShader.backFaceCulling = false;
  104555. };
  104556. /** @hidden */
  104557. EdgesRenderer.prototype._rebuild = function () {
  104558. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104559. if (buffer) {
  104560. buffer._rebuild();
  104561. }
  104562. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104563. if (buffer) {
  104564. buffer._rebuild();
  104565. }
  104566. var scene = this._source.getScene();
  104567. var engine = scene.getEngine();
  104568. this._ib = engine.createIndexBuffer(this._linesIndices);
  104569. };
  104570. /**
  104571. * Releases the required resources for the edges renderer
  104572. */
  104573. EdgesRenderer.prototype.dispose = function () {
  104574. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  104575. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  104576. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  104577. if (buffer) {
  104578. buffer.dispose();
  104579. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  104580. }
  104581. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  104582. if (buffer) {
  104583. buffer.dispose();
  104584. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  104585. }
  104586. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  104587. this._lineShader.dispose();
  104588. };
  104589. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  104590. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  104591. return 0;
  104592. }
  104593. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  104594. return 1;
  104595. }
  104596. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  104597. return 2;
  104598. }
  104599. return -1;
  104600. };
  104601. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  104602. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  104603. return 0;
  104604. }
  104605. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  104606. return 1;
  104607. }
  104608. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  104609. return 2;
  104610. }
  104611. return -1;
  104612. };
  104613. /**
  104614. * Checks if the pair of p0 and p1 is en edge
  104615. * @param faceIndex
  104616. * @param edge
  104617. * @param faceNormals
  104618. * @param p0
  104619. * @param p1
  104620. * @private
  104621. */
  104622. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104623. var needToCreateLine;
  104624. if (edge === undefined) {
  104625. needToCreateLine = true;
  104626. }
  104627. else {
  104628. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  104629. needToCreateLine = dotProduct < this._epsilon;
  104630. }
  104631. if (needToCreateLine) {
  104632. var offset = this._linesPositions.length / 3;
  104633. var normal = p0.subtract(p1);
  104634. normal.normalize();
  104635. // Positions
  104636. this._linesPositions.push(p0.x);
  104637. this._linesPositions.push(p0.y);
  104638. this._linesPositions.push(p0.z);
  104639. this._linesPositions.push(p0.x);
  104640. this._linesPositions.push(p0.y);
  104641. this._linesPositions.push(p0.z);
  104642. this._linesPositions.push(p1.x);
  104643. this._linesPositions.push(p1.y);
  104644. this._linesPositions.push(p1.z);
  104645. this._linesPositions.push(p1.x);
  104646. this._linesPositions.push(p1.y);
  104647. this._linesPositions.push(p1.z);
  104648. // Normals
  104649. this._linesNormals.push(p1.x);
  104650. this._linesNormals.push(p1.y);
  104651. this._linesNormals.push(p1.z);
  104652. this._linesNormals.push(-1);
  104653. this._linesNormals.push(p1.x);
  104654. this._linesNormals.push(p1.y);
  104655. this._linesNormals.push(p1.z);
  104656. this._linesNormals.push(1);
  104657. this._linesNormals.push(p0.x);
  104658. this._linesNormals.push(p0.y);
  104659. this._linesNormals.push(p0.z);
  104660. this._linesNormals.push(-1);
  104661. this._linesNormals.push(p0.x);
  104662. this._linesNormals.push(p0.y);
  104663. this._linesNormals.push(p0.z);
  104664. this._linesNormals.push(1);
  104665. // Indices
  104666. this._linesIndices.push(offset);
  104667. this._linesIndices.push(offset + 1);
  104668. this._linesIndices.push(offset + 2);
  104669. this._linesIndices.push(offset);
  104670. this._linesIndices.push(offset + 2);
  104671. this._linesIndices.push(offset + 3);
  104672. }
  104673. };
  104674. /**
  104675. * Generates lines edges from adjacencjes
  104676. * @private
  104677. */
  104678. EdgesRenderer.prototype._generateEdgesLines = function () {
  104679. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104680. var indices = this._source.getIndices();
  104681. if (!indices || !positions) {
  104682. return;
  104683. }
  104684. // First let's find adjacencies
  104685. var adjacencies = new Array();
  104686. var faceNormals = new Array();
  104687. var index;
  104688. var faceAdjacencies;
  104689. // Prepare faces
  104690. for (index = 0; index < indices.length; index += 3) {
  104691. faceAdjacencies = new FaceAdjacencies();
  104692. var p0Index = indices[index];
  104693. var p1Index = indices[index + 1];
  104694. var p2Index = indices[index + 2];
  104695. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  104696. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  104697. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  104698. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  104699. faceNormal.normalize();
  104700. faceNormals.push(faceNormal);
  104701. adjacencies.push(faceAdjacencies);
  104702. }
  104703. // Scan
  104704. for (index = 0; index < adjacencies.length; index++) {
  104705. faceAdjacencies = adjacencies[index];
  104706. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  104707. var otherFaceAdjacencies = adjacencies[otherIndex];
  104708. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  104709. break;
  104710. }
  104711. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  104712. continue;
  104713. }
  104714. var otherP0 = indices[otherIndex * 3];
  104715. var otherP1 = indices[otherIndex * 3 + 1];
  104716. var otherP2 = indices[otherIndex * 3 + 2];
  104717. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  104718. var otherEdgeIndex = 0;
  104719. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  104720. continue;
  104721. }
  104722. switch (edgeIndex) {
  104723. case 0:
  104724. if (this._checkVerticesInsteadOfIndices) {
  104725. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104726. }
  104727. else {
  104728. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  104729. }
  104730. break;
  104731. case 1:
  104732. if (this._checkVerticesInsteadOfIndices) {
  104733. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104734. }
  104735. else {
  104736. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  104737. }
  104738. break;
  104739. case 2:
  104740. if (this._checkVerticesInsteadOfIndices) {
  104741. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  104742. }
  104743. else {
  104744. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  104745. }
  104746. break;
  104747. }
  104748. if (otherEdgeIndex === -1) {
  104749. continue;
  104750. }
  104751. faceAdjacencies.edges[edgeIndex] = otherIndex;
  104752. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  104753. faceAdjacencies.edgesConnectedCount++;
  104754. otherFaceAdjacencies.edgesConnectedCount++;
  104755. if (faceAdjacencies.edgesConnectedCount === 3) {
  104756. break;
  104757. }
  104758. }
  104759. }
  104760. }
  104761. // Create lines
  104762. for (index = 0; index < adjacencies.length; index++) {
  104763. // 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
  104764. var current = adjacencies[index];
  104765. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104766. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  104767. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  104768. }
  104769. // Merge into a single mesh
  104770. var engine = this._source.getScene().getEngine();
  104771. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104772. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104773. this._ib = engine.createIndexBuffer(this._linesIndices);
  104774. this._indicesCount = this._linesIndices.length;
  104775. };
  104776. /**
  104777. * Checks wether or not the edges renderer is ready to render.
  104778. * @return true if ready, otherwise false.
  104779. */
  104780. EdgesRenderer.prototype.isReady = function () {
  104781. return this._lineShader.isReady();
  104782. };
  104783. /**
  104784. * Renders the edges of the attached mesh,
  104785. */
  104786. EdgesRenderer.prototype.render = function () {
  104787. var scene = this._source.getScene();
  104788. if (!this.isReady() || !scene.activeCamera) {
  104789. return;
  104790. }
  104791. var engine = scene.getEngine();
  104792. this._lineShader._preBind();
  104793. if (this._source.edgesColor.a !== 1) {
  104794. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  104795. }
  104796. else {
  104797. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  104798. }
  104799. // VBOs
  104800. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  104801. scene.resetCachedMaterial();
  104802. this._lineShader.setColor4("color", this._source.edgesColor);
  104803. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  104804. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  104805. }
  104806. else {
  104807. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  104808. }
  104809. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  104810. this._lineShader.bind(this._source.getWorldMatrix());
  104811. // Draw order
  104812. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  104813. this._lineShader.unbind();
  104814. };
  104815. return EdgesRenderer;
  104816. }());
  104817. BABYLON.EdgesRenderer = EdgesRenderer;
  104818. })(BABYLON || (BABYLON = {}));
  104819. //# sourceMappingURL=babylon.edgesRenderer.js.map
  104820. var BABYLON;
  104821. (function (BABYLON) {
  104822. /**
  104823. * FaceAdjacencies Helper class to generate edges
  104824. */
  104825. var FaceAdjacencies = /** @class */ (function () {
  104826. function FaceAdjacencies() {
  104827. this.edges = new Array();
  104828. this.edgesConnectedCount = 0;
  104829. }
  104830. return FaceAdjacencies;
  104831. }());
  104832. /**
  104833. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  104834. */
  104835. var LineEdgesRenderer = /** @class */ (function (_super) {
  104836. __extends(LineEdgesRenderer, _super);
  104837. /**
  104838. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  104839. * @param source LineMesh used to generate edges
  104840. * @param epsilon not important (specified angle for edge detection)
  104841. * @param checkVerticesInsteadOfIndices not important for LineMesh
  104842. */
  104843. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  104844. if (epsilon === void 0) { epsilon = 0.95; }
  104845. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  104846. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  104847. _this._generateEdgesLines();
  104848. return _this;
  104849. }
  104850. /**
  104851. * Always create the edge since its a line so only important things are p0 and p1
  104852. * @param faceIndex not important for LineMesh
  104853. * @param edge not important for LineMesh
  104854. * @param faceNormals not important for LineMesh
  104855. * @param p0 beginnig of line
  104856. * @param p1 end of line
  104857. */
  104858. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  104859. var offset = this._linesPositions.length / 3;
  104860. var normal = p0.subtract(p1);
  104861. normal.normalize();
  104862. // Positions
  104863. this._linesPositions.push(p0.x);
  104864. this._linesPositions.push(p0.y);
  104865. this._linesPositions.push(p0.z);
  104866. this._linesPositions.push(p0.x);
  104867. this._linesPositions.push(p0.y);
  104868. this._linesPositions.push(p0.z);
  104869. this._linesPositions.push(p1.x);
  104870. this._linesPositions.push(p1.y);
  104871. this._linesPositions.push(p1.z);
  104872. this._linesPositions.push(p1.x);
  104873. this._linesPositions.push(p1.y);
  104874. this._linesPositions.push(p1.z);
  104875. // Normals
  104876. this._linesNormals.push(p1.x);
  104877. this._linesNormals.push(p1.y);
  104878. this._linesNormals.push(p1.z);
  104879. this._linesNormals.push(-1);
  104880. this._linesNormals.push(p1.x);
  104881. this._linesNormals.push(p1.y);
  104882. this._linesNormals.push(p1.z);
  104883. this._linesNormals.push(1);
  104884. this._linesNormals.push(p0.x);
  104885. this._linesNormals.push(p0.y);
  104886. this._linesNormals.push(p0.z);
  104887. this._linesNormals.push(-1);
  104888. this._linesNormals.push(p0.x);
  104889. this._linesNormals.push(p0.y);
  104890. this._linesNormals.push(p0.z);
  104891. this._linesNormals.push(1);
  104892. // Indices
  104893. this._linesIndices.push(offset);
  104894. this._linesIndices.push(offset + 1);
  104895. this._linesIndices.push(offset + 2);
  104896. this._linesIndices.push(offset);
  104897. this._linesIndices.push(offset + 2);
  104898. this._linesIndices.push(offset + 3);
  104899. };
  104900. /**
  104901. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  104902. */
  104903. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  104904. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  104905. var indices = this._source.getIndices();
  104906. if (!indices || !positions) {
  104907. return;
  104908. }
  104909. // First let's find adjacencies
  104910. var adjacencies = new Array();
  104911. var faceNormals = new Array();
  104912. var index;
  104913. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  104914. var currentAdjecancy = new FaceAdjacencies();
  104915. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  104916. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  104917. adjacencies.push(currentAdjecancy);
  104918. }
  104919. // Create lines
  104920. for (index = 0; index < adjacencies.length; index++) {
  104921. // 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
  104922. var current = adjacencies[index];
  104923. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  104924. }
  104925. // Merge into a single mesh
  104926. var engine = this._source.getScene().getEngine();
  104927. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  104928. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  104929. this._ib = engine.createIndexBuffer(this._linesIndices);
  104930. this._indicesCount = this._linesIndices.length;
  104931. };
  104932. return LineEdgesRenderer;
  104933. }(BABYLON.EdgesRenderer));
  104934. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  104935. })(BABYLON || (BABYLON = {}));
  104936. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  104937. var BABYLON;
  104938. (function (BABYLON) {
  104939. // Adds the parser to the scene parsers.
  104940. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  104941. if (parsedData.effectLayers) {
  104942. if (!container.effectLayers) {
  104943. container.effectLayers = new Array();
  104944. }
  104945. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  104946. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  104947. container.effectLayers.push(effectLayer);
  104948. }
  104949. }
  104950. });
  104951. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  104952. var index = this.effectLayers.indexOf(toRemove);
  104953. if (index !== -1) {
  104954. this.effectLayers.splice(index, 1);
  104955. }
  104956. return index;
  104957. };
  104958. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  104959. this.effectLayers.push(newEffectLayer);
  104960. };
  104961. /**
  104962. * Defines the layer scene component responsible to manage any effect layers
  104963. * in a given scene.
  104964. */
  104965. var EffectLayerSceneComponent = /** @class */ (function () {
  104966. /**
  104967. * Creates a new instance of the component for the given scene
  104968. * @param scene Defines the scene to register the component in
  104969. */
  104970. function EffectLayerSceneComponent(scene) {
  104971. /**
  104972. * The component name helpfull to identify the component in the list of scene components.
  104973. */
  104974. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  104975. this._renderEffects = false;
  104976. this._needStencil = false;
  104977. this._previousStencilState = false;
  104978. this.scene = scene;
  104979. this._engine = scene.getEngine();
  104980. scene.effectLayers = new Array();
  104981. }
  104982. /**
  104983. * Registers the component in a given scene
  104984. */
  104985. EffectLayerSceneComponent.prototype.register = function () {
  104986. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  104987. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  104988. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  104989. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  104990. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  104991. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  104992. };
  104993. /**
  104994. * Rebuilds the elements related to this component in case of
  104995. * context lost for instance.
  104996. */
  104997. EffectLayerSceneComponent.prototype.rebuild = function () {
  104998. var layers = this.scene.effectLayers;
  104999. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  105000. var effectLayer = layers_1[_i];
  105001. effectLayer._rebuild();
  105002. }
  105003. };
  105004. /**
  105005. * Serializes the component data to the specified json object
  105006. * @param serializationObject The object to serialize to
  105007. */
  105008. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  105009. // Effect layers
  105010. serializationObject.effectLayers = [];
  105011. var layers = this.scene.effectLayers;
  105012. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  105013. var effectLayer = layers_2[_i];
  105014. if (effectLayer.serialize) {
  105015. serializationObject.effectLayers.push(effectLayer.serialize());
  105016. }
  105017. }
  105018. };
  105019. /**
  105020. * Adds all the element from the container to the scene
  105021. * @param container the container holding the elements
  105022. */
  105023. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  105024. var _this = this;
  105025. if (!container.effectLayers) {
  105026. return;
  105027. }
  105028. container.effectLayers.forEach(function (o) {
  105029. _this.scene.addEffectLayer(o);
  105030. });
  105031. };
  105032. /**
  105033. * Removes all the elements in the container from the scene
  105034. * @param container contains the elements to remove
  105035. */
  105036. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  105037. var _this = this;
  105038. if (!container.effectLayers) {
  105039. return;
  105040. }
  105041. container.effectLayers.forEach(function (o) {
  105042. _this.scene.removeEffectLayer(o);
  105043. });
  105044. };
  105045. /**
  105046. * Disposes the component and the associated ressources.
  105047. */
  105048. EffectLayerSceneComponent.prototype.dispose = function () {
  105049. var layers = this.scene.effectLayers;
  105050. while (layers.length) {
  105051. layers[0].dispose();
  105052. }
  105053. };
  105054. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  105055. var layers = this.scene.effectLayers;
  105056. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  105057. var layer = layers_3[_i];
  105058. if (!layer.hasMesh(mesh)) {
  105059. continue;
  105060. }
  105061. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  105062. var subMesh = _b[_a];
  105063. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  105064. return false;
  105065. }
  105066. }
  105067. }
  105068. return true;
  105069. };
  105070. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  105071. this._renderEffects = false;
  105072. this._needStencil = false;
  105073. var layers = this.scene.effectLayers;
  105074. if (layers && layers.length > 0) {
  105075. this._previousStencilState = this._engine.getStencilBuffer();
  105076. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  105077. var effectLayer = layers_4[_i];
  105078. if (effectLayer.shouldRender() &&
  105079. (!effectLayer.camera ||
  105080. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  105081. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  105082. this._renderEffects = true;
  105083. this._needStencil = this._needStencil || effectLayer.needStencil();
  105084. var renderTarget = effectLayer._mainTexture;
  105085. if (renderTarget._shouldRender()) {
  105086. this.scene.incrementRenderId();
  105087. renderTarget.render(false, false);
  105088. }
  105089. }
  105090. }
  105091. this.scene.incrementRenderId();
  105092. }
  105093. };
  105094. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  105095. // Activate effect Layer stencil
  105096. if (this._needStencil) {
  105097. this._engine.setStencilBuffer(true);
  105098. }
  105099. };
  105100. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  105101. // Restore effect Layer stencil
  105102. if (this._needStencil) {
  105103. this._engine.setStencilBuffer(this._previousStencilState);
  105104. }
  105105. };
  105106. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  105107. if (this._renderEffects) {
  105108. this._engine.setDepthBuffer(false);
  105109. var layers = this.scene.effectLayers;
  105110. for (var i = 0; i < layers.length; i++) {
  105111. var effectLayer = layers[i];
  105112. if (effectLayer.renderingGroupId === renderingGroupId) {
  105113. if (effectLayer.shouldRender()) {
  105114. effectLayer.render();
  105115. }
  105116. }
  105117. }
  105118. this._engine.setDepthBuffer(true);
  105119. }
  105120. };
  105121. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  105122. if (this._renderEffects) {
  105123. this._draw(-1);
  105124. }
  105125. };
  105126. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  105127. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  105128. this._draw(index);
  105129. }
  105130. };
  105131. return EffectLayerSceneComponent;
  105132. }());
  105133. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  105134. })(BABYLON || (BABYLON = {}));
  105135. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  105136. var __assign = (this && this.__assign) || function () {
  105137. __assign = Object.assign || function(t) {
  105138. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105139. s = arguments[i];
  105140. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105141. t[p] = s[p];
  105142. }
  105143. return t;
  105144. };
  105145. return __assign.apply(this, arguments);
  105146. };
  105147. var BABYLON;
  105148. (function (BABYLON) {
  105149. /**
  105150. * The effect layer Helps adding post process effect blended with the main pass.
  105151. *
  105152. * This can be for instance use to generate glow or higlight effects on the scene.
  105153. *
  105154. * The effect layer class can not be used directly and is intented to inherited from to be
  105155. * customized per effects.
  105156. */
  105157. var EffectLayer = /** @class */ (function () {
  105158. /**
  105159. * Instantiates a new effect Layer and references it in the scene.
  105160. * @param name The name of the layer
  105161. * @param scene The scene to use the layer in
  105162. */
  105163. function EffectLayer(
  105164. /** The Friendly of the effect in the scene */
  105165. name, scene) {
  105166. this._vertexBuffers = {};
  105167. this._maxSize = 0;
  105168. this._mainTextureDesiredSize = { width: 0, height: 0 };
  105169. this._shouldRender = true;
  105170. this._postProcesses = [];
  105171. this._textures = [];
  105172. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  105173. /**
  105174. * The clear color of the texture used to generate the glow map.
  105175. */
  105176. this.neutralColor = new BABYLON.Color4();
  105177. /**
  105178. * Specifies wether the highlight layer is enabled or not.
  105179. */
  105180. this.isEnabled = true;
  105181. /**
  105182. * An event triggered when the effect layer has been disposed.
  105183. */
  105184. this.onDisposeObservable = new BABYLON.Observable();
  105185. /**
  105186. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  105187. */
  105188. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  105189. /**
  105190. * An event triggered when the generated texture is being merged in the scene.
  105191. */
  105192. this.onBeforeComposeObservable = new BABYLON.Observable();
  105193. /**
  105194. * An event triggered when the generated texture has been merged in the scene.
  105195. */
  105196. this.onAfterComposeObservable = new BABYLON.Observable();
  105197. /**
  105198. * An event triggered when the efffect layer changes its size.
  105199. */
  105200. this.onSizeChangedObservable = new BABYLON.Observable();
  105201. this.name = name;
  105202. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  105203. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  105204. if (!component) {
  105205. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  105206. this._scene._addComponent(component);
  105207. }
  105208. this._engine = this._scene.getEngine();
  105209. this._maxSize = this._engine.getCaps().maxTextureSize;
  105210. this._scene.effectLayers.push(this);
  105211. // Generate Buffers
  105212. this._generateIndexBuffer();
  105213. this._genrateVertexBuffer();
  105214. }
  105215. Object.defineProperty(EffectLayer.prototype, "camera", {
  105216. /**
  105217. * Gets the camera attached to the layer.
  105218. */
  105219. get: function () {
  105220. return this._effectLayerOptions.camera;
  105221. },
  105222. enumerable: true,
  105223. configurable: true
  105224. });
  105225. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  105226. /**
  105227. * Gets the rendering group id the layer should render in.
  105228. */
  105229. get: function () {
  105230. return this._effectLayerOptions.renderingGroupId;
  105231. },
  105232. enumerable: true,
  105233. configurable: true
  105234. });
  105235. /**
  105236. * Initializes the effect layer with the required options.
  105237. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  105238. */
  105239. EffectLayer.prototype._init = function (options) {
  105240. // Adapt options
  105241. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  105242. this._setMainTextureSize();
  105243. this._createMainTexture();
  105244. this._createTextureAndPostProcesses();
  105245. this._mergeEffect = this._createMergeEffect();
  105246. };
  105247. /**
  105248. * Generates the index buffer of the full screen quad blending to the main canvas.
  105249. */
  105250. EffectLayer.prototype._generateIndexBuffer = function () {
  105251. // Indices
  105252. var indices = [];
  105253. indices.push(0);
  105254. indices.push(1);
  105255. indices.push(2);
  105256. indices.push(0);
  105257. indices.push(2);
  105258. indices.push(3);
  105259. this._indexBuffer = this._engine.createIndexBuffer(indices);
  105260. };
  105261. /**
  105262. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  105263. */
  105264. EffectLayer.prototype._genrateVertexBuffer = function () {
  105265. // VBO
  105266. var vertices = [];
  105267. vertices.push(1, 1);
  105268. vertices.push(-1, 1);
  105269. vertices.push(-1, -1);
  105270. vertices.push(1, -1);
  105271. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  105272. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  105273. };
  105274. /**
  105275. * Sets the main texture desired size which is the closest power of two
  105276. * of the engine canvas size.
  105277. */
  105278. EffectLayer.prototype._setMainTextureSize = function () {
  105279. if (this._effectLayerOptions.mainTextureFixedSize) {
  105280. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  105281. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  105282. }
  105283. else {
  105284. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  105285. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  105286. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  105287. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  105288. }
  105289. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  105290. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  105291. };
  105292. /**
  105293. * Creates the main texture for the effect layer.
  105294. */
  105295. EffectLayer.prototype._createMainTexture = function () {
  105296. var _this = this;
  105297. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  105298. width: this._mainTextureDesiredSize.width,
  105299. height: this._mainTextureDesiredSize.height
  105300. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  105301. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  105302. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105303. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105304. this._mainTexture.anisotropicFilteringLevel = 1;
  105305. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105306. this._mainTexture.renderParticles = false;
  105307. this._mainTexture.renderList = null;
  105308. this._mainTexture.ignoreCameraViewport = true;
  105309. // Custom render function
  105310. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  105311. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  105312. var index;
  105313. var engine = _this._scene.getEngine();
  105314. if (depthOnlySubMeshes.length) {
  105315. engine.setColorWrite(false);
  105316. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  105317. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  105318. }
  105319. engine.setColorWrite(true);
  105320. }
  105321. for (index = 0; index < opaqueSubMeshes.length; index++) {
  105322. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  105323. }
  105324. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  105325. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  105326. }
  105327. for (index = 0; index < transparentSubMeshes.length; index++) {
  105328. _this._renderSubMesh(transparentSubMeshes.data[index]);
  105329. }
  105330. };
  105331. this._mainTexture.onClearObservable.add(function (engine) {
  105332. engine.clear(_this.neutralColor, true, true, true);
  105333. });
  105334. };
  105335. /**
  105336. * Checks for the readiness of the element composing the layer.
  105337. * @param subMesh the mesh to check for
  105338. * @param useInstances specify wether or not to use instances to render the mesh
  105339. * @param emissiveTexture the associated emissive texture used to generate the glow
  105340. * @return true if ready otherwise, false
  105341. */
  105342. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  105343. var material = subMesh.getMaterial();
  105344. if (!material) {
  105345. return false;
  105346. }
  105347. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  105348. return false;
  105349. }
  105350. var defines = [];
  105351. var attribs = [BABYLON.VertexBuffer.PositionKind];
  105352. var mesh = subMesh.getMesh();
  105353. var uv1 = false;
  105354. var uv2 = false;
  105355. // Alpha test
  105356. if (material && material.needAlphaTesting()) {
  105357. var alphaTexture = material.getAlphaTestTexture();
  105358. if (alphaTexture) {
  105359. defines.push("#define ALPHATEST");
  105360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105361. alphaTexture.coordinatesIndex === 1) {
  105362. defines.push("#define DIFFUSEUV2");
  105363. uv2 = true;
  105364. }
  105365. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105366. defines.push("#define DIFFUSEUV1");
  105367. uv1 = true;
  105368. }
  105369. }
  105370. }
  105371. // Emissive
  105372. if (emissiveTexture) {
  105373. defines.push("#define EMISSIVE");
  105374. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  105375. emissiveTexture.coordinatesIndex === 1) {
  105376. defines.push("#define EMISSIVEUV2");
  105377. uv2 = true;
  105378. }
  105379. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  105380. defines.push("#define EMISSIVEUV1");
  105381. uv1 = true;
  105382. }
  105383. }
  105384. if (uv1) {
  105385. attribs.push(BABYLON.VertexBuffer.UVKind);
  105386. defines.push("#define UV1");
  105387. }
  105388. if (uv2) {
  105389. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  105390. defines.push("#define UV2");
  105391. }
  105392. // Bones
  105393. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  105394. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  105395. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  105396. if (mesh.numBoneInfluencers > 4) {
  105397. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  105398. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  105399. }
  105400. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  105401. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  105402. }
  105403. else {
  105404. defines.push("#define NUM_BONE_INFLUENCERS 0");
  105405. }
  105406. // Morph targets
  105407. var manager = mesh.morphTargetManager;
  105408. var morphInfluencers = 0;
  105409. if (manager) {
  105410. if (manager.numInfluencers > 0) {
  105411. defines.push("#define MORPHTARGETS");
  105412. morphInfluencers = manager.numInfluencers;
  105413. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  105414. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  105415. }
  105416. }
  105417. // Instances
  105418. if (useInstances) {
  105419. defines.push("#define INSTANCES");
  105420. attribs.push("world0");
  105421. attribs.push("world1");
  105422. attribs.push("world2");
  105423. attribs.push("world3");
  105424. }
  105425. // Get correct effect
  105426. var join = defines.join("\n");
  105427. if (this._cachedDefines !== join) {
  105428. this._cachedDefines = join;
  105429. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  105430. }
  105431. return this._effectLayerMapGenerationEffect.isReady();
  105432. };
  105433. /**
  105434. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  105435. */
  105436. EffectLayer.prototype.render = function () {
  105437. var currentEffect = this._mergeEffect;
  105438. // Check
  105439. if (!currentEffect.isReady())
  105440. return;
  105441. for (var i = 0; i < this._postProcesses.length; i++) {
  105442. if (!this._postProcesses[i].isReady()) {
  105443. return;
  105444. }
  105445. }
  105446. var engine = this._scene.getEngine();
  105447. this.onBeforeComposeObservable.notifyObservers(this);
  105448. // Render
  105449. engine.enableEffect(currentEffect);
  105450. engine.setState(false);
  105451. // VBOs
  105452. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  105453. // Cache
  105454. var previousAlphaMode = engine.getAlphaMode();
  105455. // Go Blend.
  105456. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  105457. // Blends the map on the main canvas.
  105458. this._internalRender(currentEffect);
  105459. // Restore Alpha
  105460. engine.setAlphaMode(previousAlphaMode);
  105461. this.onAfterComposeObservable.notifyObservers(this);
  105462. // Handle size changes.
  105463. var size = this._mainTexture.getSize();
  105464. this._setMainTextureSize();
  105465. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  105466. // Recreate RTT and post processes on size change.
  105467. this.onSizeChangedObservable.notifyObservers(this);
  105468. this._disposeTextureAndPostProcesses();
  105469. this._createMainTexture();
  105470. this._createTextureAndPostProcesses();
  105471. }
  105472. };
  105473. /**
  105474. * Determine if a given mesh will be used in the current effect.
  105475. * @param mesh mesh to test
  105476. * @returns true if the mesh will be used
  105477. */
  105478. EffectLayer.prototype.hasMesh = function (mesh) {
  105479. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  105480. return true;
  105481. }
  105482. return false;
  105483. };
  105484. /**
  105485. * Returns true if the layer contains information to display, otherwise false.
  105486. * @returns true if the glow layer should be rendered
  105487. */
  105488. EffectLayer.prototype.shouldRender = function () {
  105489. return this.isEnabled && this._shouldRender;
  105490. };
  105491. /**
  105492. * Returns true if the mesh should render, otherwise false.
  105493. * @param mesh The mesh to render
  105494. * @returns true if it should render otherwise false
  105495. */
  105496. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  105497. return true;
  105498. };
  105499. /**
  105500. * Returns true if the mesh should render, otherwise false.
  105501. * @param mesh The mesh to render
  105502. * @returns true if it should render otherwise false
  105503. */
  105504. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  105505. return true;
  105506. };
  105507. /**
  105508. * Renders the submesh passed in parameter to the generation map.
  105509. */
  105510. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  105511. var _this = this;
  105512. if (!this.shouldRender()) {
  105513. return;
  105514. }
  105515. var material = subMesh.getMaterial();
  105516. var mesh = subMesh.getRenderingMesh();
  105517. var scene = this._scene;
  105518. var engine = scene.getEngine();
  105519. if (!material) {
  105520. return;
  105521. }
  105522. // Do not block in blend mode.
  105523. if (material.needAlphaBlendingForMesh(mesh)) {
  105524. return;
  105525. }
  105526. // Culling
  105527. engine.setState(material.backFaceCulling);
  105528. // Managing instances
  105529. var batch = mesh._getInstancesRenderList(subMesh._id);
  105530. if (batch.mustReturn) {
  105531. return;
  105532. }
  105533. // Early Exit per mesh
  105534. if (!this._shouldRenderMesh(mesh)) {
  105535. return;
  105536. }
  105537. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  105538. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  105539. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  105540. engine.enableEffect(this._effectLayerMapGenerationEffect);
  105541. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  105542. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  105543. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  105544. // Alpha test
  105545. if (material && material.needAlphaTesting()) {
  105546. var alphaTexture = material.getAlphaTestTexture();
  105547. if (alphaTexture) {
  105548. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  105549. var textureMatrix = alphaTexture.getTextureMatrix();
  105550. if (textureMatrix) {
  105551. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  105552. }
  105553. }
  105554. }
  105555. // Glow emissive only
  105556. if (this._emissiveTextureAndColor.texture) {
  105557. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  105558. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  105559. }
  105560. // Bones
  105561. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  105562. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  105563. }
  105564. // Morph targets
  105565. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  105566. // Draw
  105567. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  105568. }
  105569. else {
  105570. // Need to reset refresh rate of the main map
  105571. this._mainTexture.resetRefreshCounter();
  105572. }
  105573. };
  105574. /**
  105575. * Rebuild the required buffers.
  105576. * @hidden Internal use only.
  105577. */
  105578. EffectLayer.prototype._rebuild = function () {
  105579. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105580. if (vb) {
  105581. vb._rebuild();
  105582. }
  105583. this._generateIndexBuffer();
  105584. };
  105585. /**
  105586. * Dispose only the render target textures and post process.
  105587. */
  105588. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  105589. this._mainTexture.dispose();
  105590. for (var i = 0; i < this._postProcesses.length; i++) {
  105591. if (this._postProcesses[i]) {
  105592. this._postProcesses[i].dispose();
  105593. }
  105594. }
  105595. this._postProcesses = [];
  105596. for (var i = 0; i < this._textures.length; i++) {
  105597. if (this._textures[i]) {
  105598. this._textures[i].dispose();
  105599. }
  105600. }
  105601. this._textures = [];
  105602. };
  105603. /**
  105604. * Dispose the highlight layer and free resources.
  105605. */
  105606. EffectLayer.prototype.dispose = function () {
  105607. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  105608. if (vertexBuffer) {
  105609. vertexBuffer.dispose();
  105610. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  105611. }
  105612. if (this._indexBuffer) {
  105613. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  105614. this._indexBuffer = null;
  105615. }
  105616. // Clean textures and post processes
  105617. this._disposeTextureAndPostProcesses();
  105618. // Remove from scene
  105619. var index = this._scene.effectLayers.indexOf(this, 0);
  105620. if (index > -1) {
  105621. this._scene.effectLayers.splice(index, 1);
  105622. }
  105623. // Callback
  105624. this.onDisposeObservable.notifyObservers(this);
  105625. this.onDisposeObservable.clear();
  105626. this.onBeforeRenderMainTextureObservable.clear();
  105627. this.onBeforeComposeObservable.clear();
  105628. this.onAfterComposeObservable.clear();
  105629. this.onSizeChangedObservable.clear();
  105630. };
  105631. /**
  105632. * Gets the class name of the effect layer
  105633. * @returns the string with the class name of the effect layer
  105634. */
  105635. EffectLayer.prototype.getClassName = function () {
  105636. return "EffectLayer";
  105637. };
  105638. /**
  105639. * Creates an effect layer from parsed effect layer data
  105640. * @param parsedEffectLayer defines effect layer data
  105641. * @param scene defines the current scene
  105642. * @param rootUrl defines the root URL containing the effect layer information
  105643. * @returns a parsed effect Layer
  105644. */
  105645. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  105646. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  105647. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  105648. };
  105649. __decorate([
  105650. BABYLON.serialize()
  105651. ], EffectLayer.prototype, "name", void 0);
  105652. __decorate([
  105653. BABYLON.serializeAsColor4()
  105654. ], EffectLayer.prototype, "neutralColor", void 0);
  105655. __decorate([
  105656. BABYLON.serialize()
  105657. ], EffectLayer.prototype, "isEnabled", void 0);
  105658. __decorate([
  105659. BABYLON.serializeAsCameraReference()
  105660. ], EffectLayer.prototype, "camera", null);
  105661. __decorate([
  105662. BABYLON.serialize()
  105663. ], EffectLayer.prototype, "renderingGroupId", null);
  105664. return EffectLayer;
  105665. }());
  105666. BABYLON.EffectLayer = EffectLayer;
  105667. })(BABYLON || (BABYLON = {}));
  105668. //# sourceMappingURL=babylon.effectLayer.js.map
  105669. var BABYLON;
  105670. (function (BABYLON) {
  105671. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  105672. for (var index = 0; index < this.effectLayers.length; index++) {
  105673. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  105674. return this.effectLayers[index];
  105675. }
  105676. }
  105677. return null;
  105678. };
  105679. /**
  105680. * Special Glow Blur post process only blurring the alpha channel
  105681. * It enforces keeping the most luminous color in the color channel.
  105682. */
  105683. var GlowBlurPostProcess = /** @class */ (function (_super) {
  105684. __extends(GlowBlurPostProcess, _super);
  105685. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  105686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  105687. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  105688. _this.direction = direction;
  105689. _this.kernel = kernel;
  105690. _this.onApplyObservable.add(function (effect) {
  105691. effect.setFloat2("screenSize", _this.width, _this.height);
  105692. effect.setVector2("direction", _this.direction);
  105693. effect.setFloat("blurWidth", _this.kernel);
  105694. });
  105695. return _this;
  105696. }
  105697. return GlowBlurPostProcess;
  105698. }(BABYLON.PostProcess));
  105699. /**
  105700. * The highlight layer Helps adding a glow effect around a mesh.
  105701. *
  105702. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105703. * glowy meshes to your scene.
  105704. *
  105705. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  105706. */
  105707. var HighlightLayer = /** @class */ (function (_super) {
  105708. __extends(HighlightLayer, _super);
  105709. /**
  105710. * Instantiates a new highlight Layer and references it to the scene..
  105711. * @param name The name of the layer
  105712. * @param scene The scene to use the layer in
  105713. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  105714. */
  105715. function HighlightLayer(name, scene, options) {
  105716. var _this = _super.call(this, name, scene) || this;
  105717. _this.name = name;
  105718. /**
  105719. * Specifies whether or not the inner glow is ACTIVE in the layer.
  105720. */
  105721. _this.innerGlow = true;
  105722. /**
  105723. * Specifies whether or not the outer glow is ACTIVE in the layer.
  105724. */
  105725. _this.outerGlow = true;
  105726. /**
  105727. * An event triggered when the highlight layer is being blurred.
  105728. */
  105729. _this.onBeforeBlurObservable = new BABYLON.Observable();
  105730. /**
  105731. * An event triggered when the highlight layer has been blurred.
  105732. */
  105733. _this.onAfterBlurObservable = new BABYLON.Observable();
  105734. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  105735. _this._meshes = {};
  105736. _this._excludedMeshes = {};
  105737. _this.neutralColor = HighlightLayer.NeutralColor;
  105738. // Warn on stencil
  105739. if (!_this._engine.isStencilEnable) {
  105740. 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 }");
  105741. }
  105742. // Adapt options
  105743. _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);
  105744. // Initialize the layer
  105745. _this._init({
  105746. alphaBlendingMode: _this._options.alphaBlendingMode,
  105747. camera: _this._options.camera,
  105748. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105749. mainTextureRatio: _this._options.mainTextureRatio,
  105750. renderingGroupId: _this._options.renderingGroupId
  105751. });
  105752. // Do not render as long as no meshes have been added
  105753. _this._shouldRender = false;
  105754. return _this;
  105755. }
  105756. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  105757. /**
  105758. * Gets the horizontal size of the blur.
  105759. */
  105760. get: function () {
  105761. return this._horizontalBlurPostprocess.kernel;
  105762. },
  105763. /**
  105764. * Specifies the horizontal size of the blur.
  105765. */
  105766. set: function (value) {
  105767. this._horizontalBlurPostprocess.kernel = value;
  105768. },
  105769. enumerable: true,
  105770. configurable: true
  105771. });
  105772. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  105773. /**
  105774. * Gets the vertical size of the blur.
  105775. */
  105776. get: function () {
  105777. return this._verticalBlurPostprocess.kernel;
  105778. },
  105779. /**
  105780. * Specifies the vertical size of the blur.
  105781. */
  105782. set: function (value) {
  105783. this._verticalBlurPostprocess.kernel = value;
  105784. },
  105785. enumerable: true,
  105786. configurable: true
  105787. });
  105788. /**
  105789. * Get the effect name of the layer.
  105790. * @return The effect name
  105791. */
  105792. HighlightLayer.prototype.getEffectName = function () {
  105793. return HighlightLayer.EffectName;
  105794. };
  105795. /**
  105796. * Create the merge effect. This is the shader use to blit the information back
  105797. * to the main canvas at the end of the scene rendering.
  105798. */
  105799. HighlightLayer.prototype._createMergeEffect = function () {
  105800. // Effect
  105801. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  105802. };
  105803. /**
  105804. * Creates the render target textures and post processes used in the highlight layer.
  105805. */
  105806. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  105807. var _this = this;
  105808. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  105809. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  105810. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105811. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105812. var textureType = 0;
  105813. if (this._engine.getCaps().textureHalfFloatRender) {
  105814. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105815. }
  105816. else {
  105817. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105818. }
  105819. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  105820. width: blurTextureWidth,
  105821. height: blurTextureHeight
  105822. }, this._scene, false, true, textureType);
  105823. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105824. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105825. this._blurTexture.anisotropicFilteringLevel = 16;
  105826. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  105827. this._blurTexture.renderParticles = false;
  105828. this._blurTexture.ignoreCameraViewport = true;
  105829. this._textures = [this._blurTexture];
  105830. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  105831. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105832. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  105833. effect.setTexture("textureSampler", _this._mainTexture);
  105834. });
  105835. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105836. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105837. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105838. });
  105839. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  105840. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  105841. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  105842. });
  105843. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105844. }
  105845. else {
  105846. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  105847. width: blurTextureWidth,
  105848. height: blurTextureHeight
  105849. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105850. this._horizontalBlurPostprocess.width = blurTextureWidth;
  105851. this._horizontalBlurPostprocess.height = blurTextureHeight;
  105852. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  105853. effect.setTexture("textureSampler", _this._mainTexture);
  105854. });
  105855. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  105856. width: blurTextureWidth,
  105857. height: blurTextureHeight
  105858. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105859. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  105860. }
  105861. this._mainTexture.onAfterUnbindObservable.add(function () {
  105862. _this.onBeforeBlurObservable.notifyObservers(_this);
  105863. var internalTexture = _this._blurTexture.getInternalTexture();
  105864. if (internalTexture) {
  105865. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  105866. }
  105867. _this.onAfterBlurObservable.notifyObservers(_this);
  105868. });
  105869. // Prevent autoClear.
  105870. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105871. };
  105872. /**
  105873. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105874. */
  105875. HighlightLayer.prototype.needStencil = function () {
  105876. return true;
  105877. };
  105878. /**
  105879. * Checks for the readiness of the element composing the layer.
  105880. * @param subMesh the mesh to check for
  105881. * @param useInstances specify wether or not to use instances to render the mesh
  105882. * @param emissiveTexture the associated emissive texture used to generate the glow
  105883. * @return true if ready otherwise, false
  105884. */
  105885. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  105886. var material = subMesh.getMaterial();
  105887. var mesh = subMesh.getRenderingMesh();
  105888. if (!material || !mesh || !this._meshes) {
  105889. return false;
  105890. }
  105891. var emissiveTexture = null;
  105892. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105893. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105894. emissiveTexture = material.emissiveTexture;
  105895. }
  105896. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105897. };
  105898. /**
  105899. * Implementation specific of rendering the generating effect on the main canvas.
  105900. * @param effect The effect used to render through
  105901. */
  105902. HighlightLayer.prototype._internalRender = function (effect) {
  105903. // Texture
  105904. effect.setTexture("textureSampler", this._blurTexture);
  105905. // Cache
  105906. var engine = this._engine;
  105907. var previousStencilBuffer = engine.getStencilBuffer();
  105908. var previousStencilFunction = engine.getStencilFunction();
  105909. var previousStencilMask = engine.getStencilMask();
  105910. var previousStencilOperationPass = engine.getStencilOperationPass();
  105911. var previousStencilOperationFail = engine.getStencilOperationFail();
  105912. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  105913. var previousStencilReference = engine.getStencilFunctionReference();
  105914. // Stencil operations
  105915. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  105916. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  105917. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  105918. // Draw order
  105919. engine.setStencilMask(0x00);
  105920. engine.setStencilBuffer(true);
  105921. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  105922. // 2 passes inner outer
  105923. if (this.outerGlow) {
  105924. effect.setFloat("offset", 0);
  105925. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  105926. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105927. }
  105928. if (this.innerGlow) {
  105929. effect.setFloat("offset", 1);
  105930. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  105931. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105932. }
  105933. // Restore Cache
  105934. engine.setStencilFunction(previousStencilFunction);
  105935. engine.setStencilMask(previousStencilMask);
  105936. engine.setStencilBuffer(previousStencilBuffer);
  105937. engine.setStencilOperationPass(previousStencilOperationPass);
  105938. engine.setStencilOperationFail(previousStencilOperationFail);
  105939. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  105940. engine.setStencilFunctionReference(previousStencilReference);
  105941. };
  105942. /**
  105943. * Returns true if the layer contains information to display, otherwise false.
  105944. */
  105945. HighlightLayer.prototype.shouldRender = function () {
  105946. if (_super.prototype.shouldRender.call(this)) {
  105947. return this._meshes ? true : false;
  105948. }
  105949. return false;
  105950. };
  105951. /**
  105952. * Returns true if the mesh should render, otherwise false.
  105953. * @param mesh The mesh to render
  105954. * @returns true if it should render otherwise false
  105955. */
  105956. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  105957. // Excluded Mesh
  105958. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  105959. return false;
  105960. }
  105961. ;
  105962. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105963. return false;
  105964. }
  105965. return true;
  105966. };
  105967. /**
  105968. * Sets the required values for both the emissive texture and and the main color.
  105969. */
  105970. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105971. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  105972. if (highlightLayerMesh) {
  105973. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  105974. }
  105975. else {
  105976. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105977. }
  105978. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  105979. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105980. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  105981. }
  105982. else {
  105983. this._emissiveTextureAndColor.texture = null;
  105984. }
  105985. };
  105986. /**
  105987. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  105988. * @param mesh The mesh to exclude from the highlight layer
  105989. */
  105990. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  105991. if (!this._excludedMeshes) {
  105992. return;
  105993. }
  105994. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  105995. if (!meshExcluded) {
  105996. this._excludedMeshes[mesh.uniqueId] = {
  105997. mesh: mesh,
  105998. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  105999. mesh.getEngine().setStencilBuffer(false);
  106000. }),
  106001. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  106002. mesh.getEngine().setStencilBuffer(true);
  106003. }),
  106004. };
  106005. }
  106006. };
  106007. /**
  106008. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  106009. * @param mesh The mesh to highlight
  106010. */
  106011. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  106012. if (!this._excludedMeshes) {
  106013. return;
  106014. }
  106015. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  106016. if (meshExcluded) {
  106017. if (meshExcluded.beforeRender) {
  106018. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  106019. }
  106020. if (meshExcluded.afterRender) {
  106021. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  106022. }
  106023. }
  106024. this._excludedMeshes[mesh.uniqueId] = null;
  106025. };
  106026. /**
  106027. * Determine if a given mesh will be highlighted by the current HighlightLayer
  106028. * @param mesh mesh to test
  106029. * @returns true if the mesh will be highlighted by the current HighlightLayer
  106030. */
  106031. HighlightLayer.prototype.hasMesh = function (mesh) {
  106032. if (!this._meshes) {
  106033. return false;
  106034. }
  106035. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106036. return false;
  106037. }
  106038. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  106039. };
  106040. /**
  106041. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  106042. * @param mesh The mesh to highlight
  106043. * @param color The color of the highlight
  106044. * @param glowEmissiveOnly Extract the glow from the emissive texture
  106045. */
  106046. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  106047. var _this = this;
  106048. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  106049. if (!this._meshes) {
  106050. return;
  106051. }
  106052. var meshHighlight = this._meshes[mesh.uniqueId];
  106053. if (meshHighlight) {
  106054. meshHighlight.color = color;
  106055. }
  106056. else {
  106057. this._meshes[mesh.uniqueId] = {
  106058. mesh: mesh,
  106059. color: color,
  106060. // Lambda required for capture due to Observable this context
  106061. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  106062. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  106063. _this._defaultStencilReference(mesh);
  106064. }
  106065. else {
  106066. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  106067. }
  106068. }),
  106069. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  106070. glowEmissiveOnly: glowEmissiveOnly
  106071. };
  106072. mesh.onDisposeObservable.add(function () {
  106073. _this._disposeMesh(mesh);
  106074. });
  106075. }
  106076. this._shouldRender = true;
  106077. };
  106078. /**
  106079. * Remove a mesh from the highlight layer in order to make it stop glowing.
  106080. * @param mesh The mesh to highlight
  106081. */
  106082. HighlightLayer.prototype.removeMesh = function (mesh) {
  106083. if (!this._meshes) {
  106084. return;
  106085. }
  106086. var meshHighlight = this._meshes[mesh.uniqueId];
  106087. if (meshHighlight) {
  106088. if (meshHighlight.observerHighlight) {
  106089. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106090. }
  106091. if (meshHighlight.observerDefault) {
  106092. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106093. }
  106094. delete this._meshes[mesh.uniqueId];
  106095. }
  106096. this._shouldRender = false;
  106097. for (var meshHighlightToCheck in this._meshes) {
  106098. if (this._meshes[meshHighlightToCheck]) {
  106099. this._shouldRender = true;
  106100. break;
  106101. }
  106102. }
  106103. };
  106104. /**
  106105. * Force the stencil to the normal expected value for none glowing parts
  106106. */
  106107. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  106108. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  106109. };
  106110. /**
  106111. * Free any resources and references associated to a mesh.
  106112. * Internal use
  106113. * @param mesh The mesh to free.
  106114. * @hidden
  106115. */
  106116. HighlightLayer.prototype._disposeMesh = function (mesh) {
  106117. this.removeMesh(mesh);
  106118. this.removeExcludedMesh(mesh);
  106119. };
  106120. /**
  106121. * Dispose the highlight layer and free resources.
  106122. */
  106123. HighlightLayer.prototype.dispose = function () {
  106124. if (this._meshes) {
  106125. // Clean mesh references
  106126. for (var id in this._meshes) {
  106127. var meshHighlight = this._meshes[id];
  106128. if (meshHighlight && meshHighlight.mesh) {
  106129. if (meshHighlight.observerHighlight) {
  106130. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  106131. }
  106132. if (meshHighlight.observerDefault) {
  106133. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  106134. }
  106135. }
  106136. }
  106137. this._meshes = null;
  106138. }
  106139. if (this._excludedMeshes) {
  106140. for (var id in this._excludedMeshes) {
  106141. var meshHighlight = this._excludedMeshes[id];
  106142. if (meshHighlight) {
  106143. if (meshHighlight.beforeRender) {
  106144. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  106145. }
  106146. if (meshHighlight.afterRender) {
  106147. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  106148. }
  106149. }
  106150. }
  106151. this._excludedMeshes = null;
  106152. }
  106153. _super.prototype.dispose.call(this);
  106154. };
  106155. /**
  106156. * Gets the class name of the effect layer
  106157. * @returns the string with the class name of the effect layer
  106158. */
  106159. HighlightLayer.prototype.getClassName = function () {
  106160. return "HighlightLayer";
  106161. };
  106162. /**
  106163. * Serializes this Highlight layer
  106164. * @returns a serialized Highlight layer object
  106165. */
  106166. HighlightLayer.prototype.serialize = function () {
  106167. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106168. serializationObject.customType = "BABYLON.HighlightLayer";
  106169. // Highlighted meshes
  106170. serializationObject.meshes = [];
  106171. if (this._meshes) {
  106172. for (var m in this._meshes) {
  106173. var mesh = this._meshes[m];
  106174. if (mesh) {
  106175. serializationObject.meshes.push({
  106176. glowEmissiveOnly: mesh.glowEmissiveOnly,
  106177. color: mesh.color.asArray(),
  106178. meshId: mesh.mesh.id
  106179. });
  106180. }
  106181. }
  106182. }
  106183. // Excluded meshes
  106184. serializationObject.excludedMeshes = [];
  106185. if (this._excludedMeshes) {
  106186. for (var e in this._excludedMeshes) {
  106187. var excludedMesh = this._excludedMeshes[e];
  106188. if (excludedMesh) {
  106189. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  106190. }
  106191. }
  106192. }
  106193. return serializationObject;
  106194. };
  106195. /**
  106196. * Creates a Highlight layer from parsed Highlight layer data
  106197. * @param parsedHightlightLayer defines the Highlight layer data
  106198. * @param scene defines the current scene
  106199. * @param rootUrl defines the root URL containing the Highlight layer information
  106200. * @returns a parsed Highlight layer
  106201. */
  106202. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  106203. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  106204. var index;
  106205. // Excluded meshes
  106206. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  106207. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  106208. if (mesh) {
  106209. hl.addExcludedMesh(mesh);
  106210. }
  106211. }
  106212. // Included meshes
  106213. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  106214. var highlightedMesh = parsedHightlightLayer.meshes[index];
  106215. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  106216. if (mesh) {
  106217. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  106218. }
  106219. }
  106220. return hl;
  106221. };
  106222. /**
  106223. * Effect Name of the highlight layer.
  106224. */
  106225. HighlightLayer.EffectName = "HighlightLayer";
  106226. /**
  106227. * The neutral color used during the preparation of the glow effect.
  106228. * This is black by default as the blend operation is a blend operation.
  106229. */
  106230. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  106231. /**
  106232. * Stencil value used for glowing meshes.
  106233. */
  106234. HighlightLayer.GlowingMeshStencilReference = 0x02;
  106235. /**
  106236. * Stencil value used for the other meshes in the scene.
  106237. */
  106238. HighlightLayer.NormalMeshStencilReference = 0x01;
  106239. __decorate([
  106240. BABYLON.serialize()
  106241. ], HighlightLayer.prototype, "innerGlow", void 0);
  106242. __decorate([
  106243. BABYLON.serialize()
  106244. ], HighlightLayer.prototype, "outerGlow", void 0);
  106245. __decorate([
  106246. BABYLON.serialize()
  106247. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  106248. __decorate([
  106249. BABYLON.serialize()
  106250. ], HighlightLayer.prototype, "blurVerticalSize", null);
  106251. __decorate([
  106252. BABYLON.serialize("options")
  106253. ], HighlightLayer.prototype, "_options", void 0);
  106254. return HighlightLayer;
  106255. }(BABYLON.EffectLayer));
  106256. BABYLON.HighlightLayer = HighlightLayer;
  106257. })(BABYLON || (BABYLON = {}));
  106258. //# sourceMappingURL=babylon.highlightLayer.js.map
  106259. var BABYLON;
  106260. (function (BABYLON) {
  106261. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  106262. for (var index = 0; index < this.effectLayers.length; index++) {
  106263. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  106264. return this.effectLayers[index];
  106265. }
  106266. }
  106267. return null;
  106268. };
  106269. /**
  106270. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  106271. *
  106272. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  106273. * glowy meshes to your scene.
  106274. *
  106275. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  106276. */
  106277. var GlowLayer = /** @class */ (function (_super) {
  106278. __extends(GlowLayer, _super);
  106279. /**
  106280. * Instantiates a new glow Layer and references it to the scene.
  106281. * @param name The name of the layer
  106282. * @param scene The scene to use the layer in
  106283. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  106284. */
  106285. function GlowLayer(name, scene, options) {
  106286. var _this = _super.call(this, name, scene) || this;
  106287. _this._intensity = 1.0;
  106288. _this._includedOnlyMeshes = [];
  106289. _this._excludedMeshes = [];
  106290. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  106291. // Adapt options
  106292. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  106293. // Initialize the layer
  106294. _this._init({
  106295. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  106296. camera: _this._options.camera,
  106297. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  106298. mainTextureRatio: _this._options.mainTextureRatio,
  106299. renderingGroupId: _this._options.renderingGroupId
  106300. });
  106301. return _this;
  106302. }
  106303. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  106304. /**
  106305. * Gets the kernel size of the blur.
  106306. */
  106307. get: function () {
  106308. return this._horizontalBlurPostprocess1.kernel;
  106309. },
  106310. /**
  106311. * Sets the kernel size of the blur.
  106312. */
  106313. set: function (value) {
  106314. this._horizontalBlurPostprocess1.kernel = value;
  106315. this._verticalBlurPostprocess1.kernel = value;
  106316. this._horizontalBlurPostprocess2.kernel = value;
  106317. this._verticalBlurPostprocess2.kernel = value;
  106318. },
  106319. enumerable: true,
  106320. configurable: true
  106321. });
  106322. Object.defineProperty(GlowLayer.prototype, "intensity", {
  106323. /**
  106324. * Gets the glow intensity.
  106325. */
  106326. get: function () {
  106327. return this._intensity;
  106328. },
  106329. /**
  106330. * Sets the glow intensity.
  106331. */
  106332. set: function (value) {
  106333. this._intensity = value;
  106334. },
  106335. enumerable: true,
  106336. configurable: true
  106337. });
  106338. /**
  106339. * Get the effect name of the layer.
  106340. * @return The effect name
  106341. */
  106342. GlowLayer.prototype.getEffectName = function () {
  106343. return GlowLayer.EffectName;
  106344. };
  106345. /**
  106346. * Create the merge effect. This is the shader use to blit the information back
  106347. * to the main canvas at the end of the scene rendering.
  106348. */
  106349. GlowLayer.prototype._createMergeEffect = function () {
  106350. // Effect
  106351. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  106352. };
  106353. /**
  106354. * Creates the render target textures and post processes used in the glow layer.
  106355. */
  106356. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  106357. var _this = this;
  106358. var blurTextureWidth = this._mainTextureDesiredSize.width;
  106359. var blurTextureHeight = this._mainTextureDesiredSize.height;
  106360. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  106361. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  106362. var textureType = 0;
  106363. if (this._engine.getCaps().textureHalfFloatRender) {
  106364. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  106365. }
  106366. else {
  106367. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  106368. }
  106369. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  106370. width: blurTextureWidth,
  106371. height: blurTextureHeight
  106372. }, this._scene, false, true, textureType);
  106373. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106374. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106375. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106376. this._blurTexture1.renderParticles = false;
  106377. this._blurTexture1.ignoreCameraViewport = true;
  106378. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  106379. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  106380. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  106381. width: blurTextureWidth2,
  106382. height: blurTextureHeight2
  106383. }, this._scene, false, true, textureType);
  106384. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106385. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  106386. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  106387. this._blurTexture2.renderParticles = false;
  106388. this._blurTexture2.ignoreCameraViewport = true;
  106389. this._textures = [this._blurTexture1, this._blurTexture2];
  106390. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106391. width: blurTextureWidth,
  106392. height: blurTextureHeight
  106393. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106394. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  106395. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  106396. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  106397. effect.setTexture("textureSampler", _this._mainTexture);
  106398. });
  106399. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106400. width: blurTextureWidth,
  106401. height: blurTextureHeight
  106402. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106403. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  106404. width: blurTextureWidth2,
  106405. height: blurTextureHeight2
  106406. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106407. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  106408. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  106409. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  106410. effect.setTexture("textureSampler", _this._blurTexture1);
  106411. });
  106412. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  106413. width: blurTextureWidth2,
  106414. height: blurTextureHeight2
  106415. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  106416. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106417. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  106418. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  106419. this._mainTexture.samples = this._options.mainTextureSamples;
  106420. this._mainTexture.onAfterUnbindObservable.add(function () {
  106421. var internalTexture = _this._blurTexture1.getInternalTexture();
  106422. if (internalTexture) {
  106423. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  106424. internalTexture = _this._blurTexture2.getInternalTexture();
  106425. if (internalTexture) {
  106426. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  106427. }
  106428. }
  106429. });
  106430. // Prevent autoClear.
  106431. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  106432. };
  106433. /**
  106434. * Checks for the readiness of the element composing the layer.
  106435. * @param subMesh the mesh to check for
  106436. * @param useInstances specify wether or not to use instances to render the mesh
  106437. * @param emissiveTexture the associated emissive texture used to generate the glow
  106438. * @return true if ready otherwise, false
  106439. */
  106440. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  106441. var material = subMesh.getMaterial();
  106442. var mesh = subMesh.getRenderingMesh();
  106443. if (!material || !mesh) {
  106444. return false;
  106445. }
  106446. var emissiveTexture = material.emissiveTexture;
  106447. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  106448. };
  106449. /**
  106450. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  106451. */
  106452. GlowLayer.prototype.needStencil = function () {
  106453. return false;
  106454. };
  106455. /**
  106456. * Implementation specific of rendering the generating effect on the main canvas.
  106457. * @param effect The effect used to render through
  106458. */
  106459. GlowLayer.prototype._internalRender = function (effect) {
  106460. // Texture
  106461. effect.setTexture("textureSampler", this._blurTexture1);
  106462. effect.setTexture("textureSampler2", this._blurTexture2);
  106463. effect.setFloat("offset", this._intensity);
  106464. // Cache
  106465. var engine = this._engine;
  106466. var previousStencilBuffer = engine.getStencilBuffer();
  106467. // Draw order
  106468. engine.setStencilBuffer(false);
  106469. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106470. // Draw order
  106471. engine.setStencilBuffer(previousStencilBuffer);
  106472. };
  106473. /**
  106474. * Sets the required values for both the emissive texture and and the main color.
  106475. */
  106476. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  106477. var textureLevel = 1.0;
  106478. if (this.customEmissiveTextureSelector) {
  106479. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  106480. }
  106481. else {
  106482. if (material) {
  106483. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  106484. if (this._emissiveTextureAndColor.texture) {
  106485. textureLevel = this._emissiveTextureAndColor.texture.level;
  106486. }
  106487. }
  106488. else {
  106489. this._emissiveTextureAndColor.texture = null;
  106490. }
  106491. }
  106492. if (this.customEmissiveColorSelector) {
  106493. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  106494. }
  106495. else {
  106496. if (material.emissiveColor) {
  106497. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  106498. }
  106499. else {
  106500. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  106501. }
  106502. }
  106503. };
  106504. /**
  106505. * Returns true if the mesh should render, otherwise false.
  106506. * @param mesh The mesh to render
  106507. * @returns true if it should render otherwise false
  106508. */
  106509. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  106510. return this.hasMesh(mesh);
  106511. };
  106512. /**
  106513. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  106514. * @param mesh The mesh to exclude from the glow layer
  106515. */
  106516. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  106517. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  106518. this._excludedMeshes.push(mesh.uniqueId);
  106519. }
  106520. };
  106521. /**
  106522. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  106523. * @param mesh The mesh to remove
  106524. */
  106525. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  106526. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  106527. if (index !== -1) {
  106528. this._excludedMeshes.splice(index, 1);
  106529. }
  106530. };
  106531. /**
  106532. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  106533. * @param mesh The mesh to include in the glow layer
  106534. */
  106535. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  106536. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  106537. this._includedOnlyMeshes.push(mesh.uniqueId);
  106538. }
  106539. };
  106540. /**
  106541. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  106542. * @param mesh The mesh to remove
  106543. */
  106544. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  106545. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  106546. if (index !== -1) {
  106547. this._includedOnlyMeshes.splice(index, 1);
  106548. }
  106549. };
  106550. /**
  106551. * Determine if a given mesh will be used in the glow layer
  106552. * @param mesh The mesh to test
  106553. * @returns true if the mesh will be highlighted by the current glow layer
  106554. */
  106555. GlowLayer.prototype.hasMesh = function (mesh) {
  106556. if (!_super.prototype.hasMesh.call(this, mesh)) {
  106557. return false;
  106558. }
  106559. // Included Mesh
  106560. if (this._includedOnlyMeshes.length) {
  106561. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  106562. }
  106563. ;
  106564. // Excluded Mesh
  106565. if (this._excludedMeshes.length) {
  106566. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  106567. }
  106568. ;
  106569. return true;
  106570. };
  106571. /**
  106572. * Free any resources and references associated to a mesh.
  106573. * Internal use
  106574. * @param mesh The mesh to free.
  106575. * @hidden
  106576. */
  106577. GlowLayer.prototype._disposeMesh = function (mesh) {
  106578. this.removeIncludedOnlyMesh(mesh);
  106579. this.removeExcludedMesh(mesh);
  106580. };
  106581. /**
  106582. * Gets the class name of the effect layer
  106583. * @returns the string with the class name of the effect layer
  106584. */
  106585. GlowLayer.prototype.getClassName = function () {
  106586. return "GlowLayer";
  106587. };
  106588. /**
  106589. * Serializes this glow layer
  106590. * @returns a serialized glow layer object
  106591. */
  106592. GlowLayer.prototype.serialize = function () {
  106593. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  106594. serializationObject.customType = "BABYLON.GlowLayer";
  106595. var index;
  106596. // Included meshes
  106597. serializationObject.includedMeshes = [];
  106598. if (this._includedOnlyMeshes.length) {
  106599. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  106600. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  106601. if (mesh) {
  106602. serializationObject.includedMeshes.push(mesh.id);
  106603. }
  106604. }
  106605. }
  106606. // Excluded meshes
  106607. serializationObject.excludedMeshes = [];
  106608. if (this._excludedMeshes.length) {
  106609. for (index = 0; index < this._excludedMeshes.length; index++) {
  106610. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  106611. if (mesh) {
  106612. serializationObject.excludedMeshes.push(mesh.id);
  106613. }
  106614. }
  106615. }
  106616. return serializationObject;
  106617. };
  106618. /**
  106619. * Creates a Glow Layer from parsed glow layer data
  106620. * @param parsedGlowLayer defines glow layer data
  106621. * @param scene defines the current scene
  106622. * @param rootUrl defines the root URL containing the glow layer information
  106623. * @returns a parsed Glow Layer
  106624. */
  106625. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  106626. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  106627. var index;
  106628. // Excluded meshes
  106629. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  106630. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  106631. if (mesh) {
  106632. gl.addExcludedMesh(mesh);
  106633. }
  106634. }
  106635. // Included meshes
  106636. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  106637. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  106638. if (mesh) {
  106639. gl.addIncludedOnlyMesh(mesh);
  106640. }
  106641. }
  106642. return gl;
  106643. };
  106644. /**
  106645. * Effect Name of the layer.
  106646. */
  106647. GlowLayer.EffectName = "GlowLayer";
  106648. /**
  106649. * The default blur kernel size used for the glow.
  106650. */
  106651. GlowLayer.DefaultBlurKernelSize = 32;
  106652. /**
  106653. * The default texture size ratio used for the glow.
  106654. */
  106655. GlowLayer.DefaultTextureRatio = 0.5;
  106656. __decorate([
  106657. BABYLON.serialize()
  106658. ], GlowLayer.prototype, "blurKernelSize", null);
  106659. __decorate([
  106660. BABYLON.serialize()
  106661. ], GlowLayer.prototype, "intensity", null);
  106662. __decorate([
  106663. BABYLON.serialize("options")
  106664. ], GlowLayer.prototype, "_options", void 0);
  106665. return GlowLayer;
  106666. }(BABYLON.EffectLayer));
  106667. BABYLON.GlowLayer = GlowLayer;
  106668. })(BABYLON || (BABYLON = {}));
  106669. //# sourceMappingURL=babylon.glowLayer.js.map
  106670. var BABYLON;
  106671. (function (BABYLON) {
  106672. /**
  106673. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  106674. */
  106675. var AssetTaskState;
  106676. (function (AssetTaskState) {
  106677. /**
  106678. * Initialization
  106679. */
  106680. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  106681. /**
  106682. * Running
  106683. */
  106684. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  106685. /**
  106686. * Done
  106687. */
  106688. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  106689. /**
  106690. * Error
  106691. */
  106692. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  106693. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  106694. /**
  106695. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  106696. */
  106697. var AbstractAssetTask = /** @class */ (function () {
  106698. /**
  106699. * Creates a new {BABYLON.AssetsManager}
  106700. * @param name defines the name of the task
  106701. */
  106702. function AbstractAssetTask(
  106703. /**
  106704. * Task name
  106705. */ name) {
  106706. this.name = name;
  106707. this._isCompleted = false;
  106708. this._taskState = AssetTaskState.INIT;
  106709. }
  106710. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  106711. /**
  106712. * Get if the task is completed
  106713. */
  106714. get: function () {
  106715. return this._isCompleted;
  106716. },
  106717. enumerable: true,
  106718. configurable: true
  106719. });
  106720. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  106721. /**
  106722. * Gets the current state of the task
  106723. */
  106724. get: function () {
  106725. return this._taskState;
  106726. },
  106727. enumerable: true,
  106728. configurable: true
  106729. });
  106730. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  106731. /**
  106732. * Gets the current error object (if task is in error)
  106733. */
  106734. get: function () {
  106735. return this._errorObject;
  106736. },
  106737. enumerable: true,
  106738. configurable: true
  106739. });
  106740. /**
  106741. * Internal only
  106742. * @hidden
  106743. */
  106744. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  106745. if (this._errorObject) {
  106746. return;
  106747. }
  106748. this._errorObject = {
  106749. message: message,
  106750. exception: exception
  106751. };
  106752. };
  106753. /**
  106754. * Execute the current task
  106755. * @param scene defines the scene where you want your assets to be loaded
  106756. * @param onSuccess is a callback called when the task is successfully executed
  106757. * @param onError is a callback called if an error occurs
  106758. */
  106759. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106760. var _this = this;
  106761. this._taskState = AssetTaskState.RUNNING;
  106762. this.runTask(scene, function () {
  106763. _this.onDoneCallback(onSuccess, onError);
  106764. }, function (msg, exception) {
  106765. _this.onErrorCallback(onError, msg, exception);
  106766. });
  106767. };
  106768. /**
  106769. * Execute the current task
  106770. * @param scene defines the scene where you want your assets to be loaded
  106771. * @param onSuccess is a callback called when the task is successfully executed
  106772. * @param onError is a callback called if an error occurs
  106773. */
  106774. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106775. throw new Error("runTask is not implemented");
  106776. };
  106777. /**
  106778. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  106779. * This can be used with failed tasks that have the reason for failure fixed.
  106780. */
  106781. AbstractAssetTask.prototype.reset = function () {
  106782. this._taskState = AssetTaskState.INIT;
  106783. };
  106784. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  106785. this._taskState = AssetTaskState.ERROR;
  106786. this._errorObject = {
  106787. message: message,
  106788. exception: exception
  106789. };
  106790. if (this.onError) {
  106791. this.onError(this, message, exception);
  106792. }
  106793. onError();
  106794. };
  106795. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  106796. try {
  106797. this._taskState = AssetTaskState.DONE;
  106798. this._isCompleted = true;
  106799. if (this.onSuccess) {
  106800. this.onSuccess(this);
  106801. }
  106802. onSuccess();
  106803. }
  106804. catch (e) {
  106805. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  106806. }
  106807. };
  106808. return AbstractAssetTask;
  106809. }());
  106810. BABYLON.AbstractAssetTask = AbstractAssetTask;
  106811. /**
  106812. * Class used to share progress information about assets loading
  106813. */
  106814. var AssetsProgressEvent = /** @class */ (function () {
  106815. /**
  106816. * Creates a {BABYLON.AssetsProgressEvent}
  106817. * @param remainingCount defines the number of remaining tasks to process
  106818. * @param totalCount defines the total number of tasks
  106819. * @param task defines the task that was just processed
  106820. */
  106821. function AssetsProgressEvent(remainingCount, totalCount, task) {
  106822. this.remainingCount = remainingCount;
  106823. this.totalCount = totalCount;
  106824. this.task = task;
  106825. }
  106826. return AssetsProgressEvent;
  106827. }());
  106828. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  106829. /**
  106830. * Define a task used by {BABYLON.AssetsManager} to load meshes
  106831. */
  106832. var MeshAssetTask = /** @class */ (function (_super) {
  106833. __extends(MeshAssetTask, _super);
  106834. /**
  106835. * Creates a new {BABYLON.MeshAssetTask}
  106836. * @param name defines the name of the task
  106837. * @param meshesNames defines the list of mesh's names you want to load
  106838. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  106839. * @param sceneFilename defines the filename of the scene to load from
  106840. */
  106841. function MeshAssetTask(
  106842. /**
  106843. * Defines the name of the task
  106844. */
  106845. name,
  106846. /**
  106847. * Defines the list of mesh's names you want to load
  106848. */
  106849. meshesNames,
  106850. /**
  106851. * Defines the root url to use as a base to load your meshes and associated resources
  106852. */
  106853. rootUrl,
  106854. /**
  106855. * Defines the filename of the scene to load from
  106856. */
  106857. sceneFilename) {
  106858. var _this = _super.call(this, name) || this;
  106859. _this.name = name;
  106860. _this.meshesNames = meshesNames;
  106861. _this.rootUrl = rootUrl;
  106862. _this.sceneFilename = sceneFilename;
  106863. return _this;
  106864. }
  106865. /**
  106866. * Execute the current task
  106867. * @param scene defines the scene where you want your assets to be loaded
  106868. * @param onSuccess is a callback called when the task is successfully executed
  106869. * @param onError is a callback called if an error occurs
  106870. */
  106871. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106872. var _this = this;
  106873. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  106874. _this.loadedMeshes = meshes;
  106875. _this.loadedParticleSystems = particleSystems;
  106876. _this.loadedSkeletons = skeletons;
  106877. onSuccess();
  106878. }, null, function (scene, message, exception) {
  106879. onError(message, exception);
  106880. });
  106881. };
  106882. return MeshAssetTask;
  106883. }(AbstractAssetTask));
  106884. BABYLON.MeshAssetTask = MeshAssetTask;
  106885. /**
  106886. * Define a task used by {BABYLON.AssetsManager} to load text content
  106887. */
  106888. var TextFileAssetTask = /** @class */ (function (_super) {
  106889. __extends(TextFileAssetTask, _super);
  106890. /**
  106891. * Creates a new TextFileAssetTask object
  106892. * @param name defines the name of the task
  106893. * @param url defines the location of the file to load
  106894. */
  106895. function TextFileAssetTask(
  106896. /**
  106897. * Defines the name of the task
  106898. */
  106899. name,
  106900. /**
  106901. * Defines the location of the file to load
  106902. */
  106903. url) {
  106904. var _this = _super.call(this, name) || this;
  106905. _this.name = name;
  106906. _this.url = url;
  106907. return _this;
  106908. }
  106909. /**
  106910. * Execute the current task
  106911. * @param scene defines the scene where you want your assets to be loaded
  106912. * @param onSuccess is a callback called when the task is successfully executed
  106913. * @param onError is a callback called if an error occurs
  106914. */
  106915. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106916. var _this = this;
  106917. scene._loadFile(this.url, function (data) {
  106918. _this.text = data;
  106919. onSuccess();
  106920. }, undefined, false, false, function (request, exception) {
  106921. if (request) {
  106922. onError(request.status + " " + request.statusText, exception);
  106923. }
  106924. });
  106925. };
  106926. return TextFileAssetTask;
  106927. }(AbstractAssetTask));
  106928. BABYLON.TextFileAssetTask = TextFileAssetTask;
  106929. /**
  106930. * Define a task used by {BABYLON.AssetsManager} to load binary data
  106931. */
  106932. var BinaryFileAssetTask = /** @class */ (function (_super) {
  106933. __extends(BinaryFileAssetTask, _super);
  106934. /**
  106935. * Creates a new BinaryFileAssetTask object
  106936. * @param name defines the name of the new task
  106937. * @param url defines the location of the file to load
  106938. */
  106939. function BinaryFileAssetTask(
  106940. /**
  106941. * Defines the name of the task
  106942. */
  106943. name,
  106944. /**
  106945. * Defines the location of the file to load
  106946. */
  106947. url) {
  106948. var _this = _super.call(this, name) || this;
  106949. _this.name = name;
  106950. _this.url = url;
  106951. return _this;
  106952. }
  106953. /**
  106954. * Execute the current task
  106955. * @param scene defines the scene where you want your assets to be loaded
  106956. * @param onSuccess is a callback called when the task is successfully executed
  106957. * @param onError is a callback called if an error occurs
  106958. */
  106959. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  106960. var _this = this;
  106961. scene._loadFile(this.url, function (data) {
  106962. _this.data = data;
  106963. onSuccess();
  106964. }, undefined, true, true, function (request, exception) {
  106965. if (request) {
  106966. onError(request.status + " " + request.statusText, exception);
  106967. }
  106968. });
  106969. };
  106970. return BinaryFileAssetTask;
  106971. }(AbstractAssetTask));
  106972. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  106973. /**
  106974. * Define a task used by {BABYLON.AssetsManager} to load images
  106975. */
  106976. var ImageAssetTask = /** @class */ (function (_super) {
  106977. __extends(ImageAssetTask, _super);
  106978. /**
  106979. * Creates a new ImageAssetTask
  106980. * @param name defines the name of the task
  106981. * @param url defines the location of the image to load
  106982. */
  106983. function ImageAssetTask(
  106984. /**
  106985. * Defines the name of the task
  106986. */
  106987. name,
  106988. /**
  106989. * Defines the location of the image to load
  106990. */
  106991. url) {
  106992. var _this = _super.call(this, name) || this;
  106993. _this.name = name;
  106994. _this.url = url;
  106995. return _this;
  106996. }
  106997. /**
  106998. * Execute the current task
  106999. * @param scene defines the scene where you want your assets to be loaded
  107000. * @param onSuccess is a callback called when the task is successfully executed
  107001. * @param onError is a callback called if an error occurs
  107002. */
  107003. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107004. var _this = this;
  107005. var img = new Image();
  107006. BABYLON.Tools.SetCorsBehavior(this.url, img);
  107007. img.onload = function () {
  107008. _this.image = img;
  107009. onSuccess();
  107010. };
  107011. img.onerror = function (err) {
  107012. onError("Error loading image", err);
  107013. };
  107014. img.src = this.url;
  107015. };
  107016. return ImageAssetTask;
  107017. }(AbstractAssetTask));
  107018. BABYLON.ImageAssetTask = ImageAssetTask;
  107019. /**
  107020. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  107021. */
  107022. var TextureAssetTask = /** @class */ (function (_super) {
  107023. __extends(TextureAssetTask, _super);
  107024. /**
  107025. * Creates a new TextureAssetTask object
  107026. * @param name defines the name of the task
  107027. * @param url defines the location of the file to load
  107028. * @param noMipmap defines if mipmap should not be generated (default is false)
  107029. * @param invertY defines if texture must be inverted on Y axis (default is false)
  107030. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107031. */
  107032. function TextureAssetTask(
  107033. /**
  107034. * Defines the name of the task
  107035. */
  107036. name,
  107037. /**
  107038. * Defines the location of the file to load
  107039. */
  107040. url,
  107041. /**
  107042. * Defines if mipmap should not be generated (default is false)
  107043. */
  107044. noMipmap,
  107045. /**
  107046. * Defines if texture must be inverted on Y axis (default is false)
  107047. */
  107048. invertY,
  107049. /**
  107050. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  107051. */
  107052. samplingMode) {
  107053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107054. var _this = _super.call(this, name) || this;
  107055. _this.name = name;
  107056. _this.url = url;
  107057. _this.noMipmap = noMipmap;
  107058. _this.invertY = invertY;
  107059. _this.samplingMode = samplingMode;
  107060. return _this;
  107061. }
  107062. /**
  107063. * Execute the current task
  107064. * @param scene defines the scene where you want your assets to be loaded
  107065. * @param onSuccess is a callback called when the task is successfully executed
  107066. * @param onError is a callback called if an error occurs
  107067. */
  107068. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107069. var onload = function () {
  107070. onSuccess();
  107071. };
  107072. var onerror = function (message, exception) {
  107073. onError(message, exception);
  107074. };
  107075. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  107076. };
  107077. return TextureAssetTask;
  107078. }(AbstractAssetTask));
  107079. BABYLON.TextureAssetTask = TextureAssetTask;
  107080. /**
  107081. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  107082. */
  107083. var CubeTextureAssetTask = /** @class */ (function (_super) {
  107084. __extends(CubeTextureAssetTask, _super);
  107085. /**
  107086. * Creates a new CubeTextureAssetTask
  107087. * @param name defines the name of the task
  107088. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107089. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107090. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107091. * @param files defines the explicit list of files (undefined by default)
  107092. */
  107093. function CubeTextureAssetTask(
  107094. /**
  107095. * Defines the name of the task
  107096. */
  107097. name,
  107098. /**
  107099. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  107100. */
  107101. url,
  107102. /**
  107103. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  107104. */
  107105. extensions,
  107106. /**
  107107. * Defines if mipmaps should not be generated (default is false)
  107108. */
  107109. noMipmap,
  107110. /**
  107111. * Defines the explicit list of files (undefined by default)
  107112. */
  107113. files) {
  107114. var _this = _super.call(this, name) || this;
  107115. _this.name = name;
  107116. _this.url = url;
  107117. _this.extensions = extensions;
  107118. _this.noMipmap = noMipmap;
  107119. _this.files = files;
  107120. return _this;
  107121. }
  107122. /**
  107123. * Execute the current task
  107124. * @param scene defines the scene where you want your assets to be loaded
  107125. * @param onSuccess is a callback called when the task is successfully executed
  107126. * @param onError is a callback called if an error occurs
  107127. */
  107128. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  107129. var onload = function () {
  107130. onSuccess();
  107131. };
  107132. var onerror = function (message, exception) {
  107133. onError(message, exception);
  107134. };
  107135. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  107136. };
  107137. return CubeTextureAssetTask;
  107138. }(AbstractAssetTask));
  107139. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  107140. /**
  107141. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  107142. */
  107143. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  107144. __extends(HDRCubeTextureAssetTask, _super);
  107145. /**
  107146. * Creates a new HDRCubeTextureAssetTask object
  107147. * @param name defines the name of the task
  107148. * @param url defines the location of the file to load
  107149. * @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.
  107150. * @param noMipmap defines if mipmaps should not be generated (default is false)
  107151. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107152. * @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)
  107153. * @param reserved Internal use only
  107154. */
  107155. function HDRCubeTextureAssetTask(
  107156. /**
  107157. * Defines the name of the task
  107158. */
  107159. name,
  107160. /**
  107161. * Defines the location of the file to load
  107162. */
  107163. url,
  107164. /**
  107165. * Defines the desired size (the more it increases the longer the generation will be)
  107166. */
  107167. size,
  107168. /**
  107169. * Defines if mipmaps should not be generated (default is false)
  107170. */
  107171. noMipmap,
  107172. /**
  107173. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  107174. */
  107175. generateHarmonics,
  107176. /**
  107177. * 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)
  107178. */
  107179. gammaSpace,
  107180. /**
  107181. * Internal Use Only
  107182. */
  107183. reserved) {
  107184. if (noMipmap === void 0) { noMipmap = false; }
  107185. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107186. if (gammaSpace === void 0) { gammaSpace = false; }
  107187. if (reserved === void 0) { reserved = false; }
  107188. var _this = _super.call(this, name) || this;
  107189. _this.name = name;
  107190. _this.url = url;
  107191. _this.size = size;
  107192. _this.noMipmap = noMipmap;
  107193. _this.generateHarmonics = generateHarmonics;
  107194. _this.gammaSpace = gammaSpace;
  107195. _this.reserved = reserved;
  107196. return _this;
  107197. }
  107198. /**
  107199. * Execute the current task
  107200. * @param scene defines the scene where you want your assets to be loaded
  107201. * @param onSuccess is a callback called when the task is successfully executed
  107202. * @param onError is a callback called if an error occurs
  107203. */
  107204. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  107205. var onload = function () {
  107206. onSuccess();
  107207. };
  107208. var onerror = function (message, exception) {
  107209. onError(message, exception);
  107210. };
  107211. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  107212. };
  107213. return HDRCubeTextureAssetTask;
  107214. }(AbstractAssetTask));
  107215. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  107216. /**
  107217. * This class can be used to easily import assets into a scene
  107218. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  107219. */
  107220. var AssetsManager = /** @class */ (function () {
  107221. /**
  107222. * Creates a new AssetsManager
  107223. * @param scene defines the scene to work on
  107224. */
  107225. function AssetsManager(scene) {
  107226. this._isLoading = false;
  107227. this._tasks = new Array();
  107228. this._waitingTasksCount = 0;
  107229. this._totalTasksCount = 0;
  107230. /**
  107231. * Observable called when all tasks are processed
  107232. */
  107233. this.onTaskSuccessObservable = new BABYLON.Observable();
  107234. /**
  107235. * Observable called when a task had an error
  107236. */
  107237. this.onTaskErrorObservable = new BABYLON.Observable();
  107238. /**
  107239. * Observable called when a task is successful
  107240. */
  107241. this.onTasksDoneObservable = new BABYLON.Observable();
  107242. /**
  107243. * Observable called when a task is done (whatever the result is)
  107244. */
  107245. this.onProgressObservable = new BABYLON.Observable();
  107246. /**
  107247. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  107248. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  107249. */
  107250. this.useDefaultLoadingScreen = true;
  107251. this._scene = scene;
  107252. }
  107253. /**
  107254. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  107255. * @param taskName defines the name of the new task
  107256. * @param meshesNames defines the name of meshes to load
  107257. * @param rootUrl defines the root url to use to locate files
  107258. * @param sceneFilename defines the filename of the scene file
  107259. * @returns a new {BABYLON.MeshAssetTask} object
  107260. */
  107261. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  107262. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  107263. this._tasks.push(task);
  107264. return task;
  107265. };
  107266. /**
  107267. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  107268. * @param taskName defines the name of the new task
  107269. * @param url defines the url of the file to load
  107270. * @returns a new {BABYLON.TextFileAssetTask} object
  107271. */
  107272. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  107273. var task = new TextFileAssetTask(taskName, url);
  107274. this._tasks.push(task);
  107275. return task;
  107276. };
  107277. /**
  107278. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  107279. * @param taskName defines the name of the new task
  107280. * @param url defines the url of the file to load
  107281. * @returns a new {BABYLON.BinaryFileAssetTask} object
  107282. */
  107283. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  107284. var task = new BinaryFileAssetTask(taskName, url);
  107285. this._tasks.push(task);
  107286. return task;
  107287. };
  107288. /**
  107289. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  107290. * @param taskName defines the name of the new task
  107291. * @param url defines the url of the file to load
  107292. * @returns a new {BABYLON.ImageAssetTask} object
  107293. */
  107294. AssetsManager.prototype.addImageTask = function (taskName, url) {
  107295. var task = new ImageAssetTask(taskName, url);
  107296. this._tasks.push(task);
  107297. return task;
  107298. };
  107299. /**
  107300. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  107301. * @param taskName defines the name of the new task
  107302. * @param url defines the url of the file to load
  107303. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107304. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  107305. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  107306. * @returns a new {BABYLON.TextureAssetTask} object
  107307. */
  107308. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  107309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  107310. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  107311. this._tasks.push(task);
  107312. return task;
  107313. };
  107314. /**
  107315. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  107316. * @param taskName defines the name of the new task
  107317. * @param url defines the url of the file to load
  107318. * @param extensions defines the extension to use to load the cube map (can be null)
  107319. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107320. * @param files defines the list of files to load (can be null)
  107321. * @returns a new {BABYLON.CubeTextureAssetTask} object
  107322. */
  107323. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  107324. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  107325. this._tasks.push(task);
  107326. return task;
  107327. };
  107328. /**
  107329. *
  107330. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  107331. * @param taskName defines the name of the new task
  107332. * @param url defines the url of the file to load
  107333. * @param size defines the size you want for the cubemap (can be null)
  107334. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  107335. * @param generateHarmonics defines if you want to automatically generate (true by default)
  107336. * @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)
  107337. * @param reserved Internal use only
  107338. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  107339. */
  107340. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  107341. if (noMipmap === void 0) { noMipmap = false; }
  107342. if (generateHarmonics === void 0) { generateHarmonics = true; }
  107343. if (gammaSpace === void 0) { gammaSpace = false; }
  107344. if (reserved === void 0) { reserved = false; }
  107345. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  107346. this._tasks.push(task);
  107347. return task;
  107348. };
  107349. /**
  107350. * Remove a task from the assets manager.
  107351. * @param task the task to remove
  107352. */
  107353. AssetsManager.prototype.removeTask = function (task) {
  107354. var index = this._tasks.indexOf(task);
  107355. if (index > -1) {
  107356. this._tasks.splice(index, 1);
  107357. }
  107358. };
  107359. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  107360. this._waitingTasksCount--;
  107361. try {
  107362. if (this.onProgress) {
  107363. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  107364. }
  107365. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  107366. }
  107367. catch (e) {
  107368. BABYLON.Tools.Error("Error running progress callbacks.");
  107369. console.log(e);
  107370. }
  107371. if (this._waitingTasksCount === 0) {
  107372. try {
  107373. if (this.onFinish) {
  107374. this.onFinish(this._tasks);
  107375. }
  107376. // Let's remove successfull tasks
  107377. var currentTasks = this._tasks.slice();
  107378. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  107379. var task = currentTasks_1[_i];
  107380. if (task.taskState === AssetTaskState.DONE) {
  107381. var index = this._tasks.indexOf(task);
  107382. if (index > -1) {
  107383. this._tasks.splice(index, 1);
  107384. }
  107385. }
  107386. }
  107387. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107388. }
  107389. catch (e) {
  107390. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  107391. console.log(e);
  107392. }
  107393. this._isLoading = false;
  107394. this._scene.getEngine().hideLoadingUI();
  107395. }
  107396. };
  107397. AssetsManager.prototype._runTask = function (task) {
  107398. var _this = this;
  107399. var done = function () {
  107400. try {
  107401. if (_this.onTaskSuccess) {
  107402. _this.onTaskSuccess(task);
  107403. }
  107404. _this.onTaskSuccessObservable.notifyObservers(task);
  107405. _this._decreaseWaitingTasksCount(task);
  107406. }
  107407. catch (e) {
  107408. error("Error executing task success callbacks", e);
  107409. }
  107410. };
  107411. var error = function (message, exception) {
  107412. task._setErrorObject(message, exception);
  107413. if (_this.onTaskError) {
  107414. _this.onTaskError(task);
  107415. }
  107416. _this.onTaskErrorObservable.notifyObservers(task);
  107417. _this._decreaseWaitingTasksCount(task);
  107418. };
  107419. task.run(this._scene, done, error);
  107420. };
  107421. /**
  107422. * Reset the {BABYLON.AssetsManager} and remove all tasks
  107423. * @return the current instance of the {BABYLON.AssetsManager}
  107424. */
  107425. AssetsManager.prototype.reset = function () {
  107426. this._isLoading = false;
  107427. this._tasks = new Array();
  107428. return this;
  107429. };
  107430. /**
  107431. * Start the loading process
  107432. * @return the current instance of the {BABYLON.AssetsManager}
  107433. */
  107434. AssetsManager.prototype.load = function () {
  107435. if (this._isLoading) {
  107436. return this;
  107437. }
  107438. this._isLoading = true;
  107439. this._waitingTasksCount = this._tasks.length;
  107440. this._totalTasksCount = this._tasks.length;
  107441. if (this._waitingTasksCount === 0) {
  107442. this._isLoading = false;
  107443. if (this.onFinish) {
  107444. this.onFinish(this._tasks);
  107445. }
  107446. this.onTasksDoneObservable.notifyObservers(this._tasks);
  107447. return this;
  107448. }
  107449. if (this.useDefaultLoadingScreen) {
  107450. this._scene.getEngine().displayLoadingUI();
  107451. }
  107452. for (var index = 0; index < this._tasks.length; index++) {
  107453. var task = this._tasks[index];
  107454. if (task.taskState === AssetTaskState.INIT) {
  107455. this._runTask(task);
  107456. }
  107457. }
  107458. return this;
  107459. };
  107460. return AssetsManager;
  107461. }());
  107462. BABYLON.AssetsManager = AssetsManager;
  107463. })(BABYLON || (BABYLON = {}));
  107464. //# sourceMappingURL=babylon.assetsManager.js.map
  107465. var BABYLON;
  107466. (function (BABYLON) {
  107467. var serializedGeometries = [];
  107468. var serializeGeometry = function (geometry, serializationGeometries) {
  107469. if (serializedGeometries[geometry.id]) {
  107470. return;
  107471. }
  107472. if (geometry.doNotSerialize) {
  107473. return;
  107474. }
  107475. if (geometry instanceof BABYLON.BoxGeometry) {
  107476. serializationGeometries.boxes.push(geometry.serialize());
  107477. }
  107478. else if (geometry instanceof BABYLON.SphereGeometry) {
  107479. serializationGeometries.spheres.push(geometry.serialize());
  107480. }
  107481. else if (geometry instanceof BABYLON.CylinderGeometry) {
  107482. serializationGeometries.cylinders.push(geometry.serialize());
  107483. }
  107484. else if (geometry instanceof BABYLON.TorusGeometry) {
  107485. serializationGeometries.toruses.push(geometry.serialize());
  107486. }
  107487. else if (geometry instanceof BABYLON.GroundGeometry) {
  107488. serializationGeometries.grounds.push(geometry.serialize());
  107489. }
  107490. else if (geometry instanceof BABYLON.Plane) {
  107491. serializationGeometries.planes.push(geometry.serialize());
  107492. }
  107493. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  107494. serializationGeometries.torusKnots.push(geometry.serialize());
  107495. }
  107496. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  107497. throw new Error("Unknown primitive type");
  107498. }
  107499. else {
  107500. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  107501. }
  107502. serializedGeometries[geometry.id] = true;
  107503. };
  107504. var serializeMesh = function (mesh, serializationScene) {
  107505. var serializationObject = {};
  107506. // Geometry
  107507. var geometry = mesh._geometry;
  107508. if (geometry) {
  107509. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  107510. // 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
  107511. serializeGeometry(geometry, serializationScene.geometries);
  107512. }
  107513. }
  107514. // Custom
  107515. if (mesh.serialize) {
  107516. mesh.serialize(serializationObject);
  107517. }
  107518. return serializationObject;
  107519. };
  107520. var finalizeSingleMesh = function (mesh, serializationObject) {
  107521. //only works if the mesh is already loaded
  107522. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107523. //serialize material
  107524. if (mesh.material) {
  107525. if (mesh.material instanceof BABYLON.MultiMaterial) {
  107526. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  107527. serializationObject.materials = serializationObject.materials || [];
  107528. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107529. serializationObject.multiMaterials.push(mesh.material.serialize());
  107530. var _loop_1 = function (submaterial) {
  107531. if (submaterial) {
  107532. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  107533. serializationObject.materials.push(submaterial.serialize());
  107534. }
  107535. }
  107536. };
  107537. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  107538. var submaterial = _a[_i];
  107539. _loop_1(submaterial);
  107540. }
  107541. }
  107542. }
  107543. else {
  107544. serializationObject.materials = serializationObject.materials || [];
  107545. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  107546. serializationObject.materials.push(mesh.material.serialize());
  107547. }
  107548. }
  107549. }
  107550. //serialize geometry
  107551. var geometry = mesh._geometry;
  107552. if (geometry) {
  107553. if (!serializationObject.geometries) {
  107554. serializationObject.geometries = {};
  107555. serializationObject.geometries.boxes = [];
  107556. serializationObject.geometries.spheres = [];
  107557. serializationObject.geometries.cylinders = [];
  107558. serializationObject.geometries.toruses = [];
  107559. serializationObject.geometries.grounds = [];
  107560. serializationObject.geometries.planes = [];
  107561. serializationObject.geometries.torusKnots = [];
  107562. serializationObject.geometries.vertexData = [];
  107563. }
  107564. serializeGeometry(geometry, serializationObject.geometries);
  107565. }
  107566. // Skeletons
  107567. if (mesh.skeleton) {
  107568. serializationObject.skeletons = serializationObject.skeletons || [];
  107569. serializationObject.skeletons.push(mesh.skeleton.serialize());
  107570. }
  107571. //serialize the actual mesh
  107572. serializationObject.meshes = serializationObject.meshes || [];
  107573. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107574. }
  107575. };
  107576. var SceneSerializer = /** @class */ (function () {
  107577. function SceneSerializer() {
  107578. }
  107579. SceneSerializer.ClearCache = function () {
  107580. serializedGeometries = [];
  107581. };
  107582. SceneSerializer.Serialize = function (scene) {
  107583. var serializationObject = {};
  107584. SceneSerializer.ClearCache();
  107585. // Scene
  107586. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  107587. serializationObject.autoClear = scene.autoClear;
  107588. serializationObject.clearColor = scene.clearColor.asArray();
  107589. serializationObject.ambientColor = scene.ambientColor.asArray();
  107590. serializationObject.gravity = scene.gravity.asArray();
  107591. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  107592. serializationObject.workerCollisions = scene.workerCollisions;
  107593. // Fog
  107594. if (scene.fogMode && scene.fogMode !== 0) {
  107595. serializationObject.fogMode = scene.fogMode;
  107596. serializationObject.fogColor = scene.fogColor.asArray();
  107597. serializationObject.fogStart = scene.fogStart;
  107598. serializationObject.fogEnd = scene.fogEnd;
  107599. serializationObject.fogDensity = scene.fogDensity;
  107600. }
  107601. //Physics
  107602. if (scene.isPhysicsEnabled()) {
  107603. var physicEngine = scene.getPhysicsEngine();
  107604. if (physicEngine) {
  107605. serializationObject.physicsEnabled = true;
  107606. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  107607. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  107608. }
  107609. }
  107610. // Metadata
  107611. if (scene.metadata) {
  107612. serializationObject.metadata = scene.metadata;
  107613. }
  107614. // Morph targets
  107615. serializationObject.morphTargetManagers = [];
  107616. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  107617. var abstractMesh = _a[_i];
  107618. var manager = abstractMesh.morphTargetManager;
  107619. if (manager) {
  107620. serializationObject.morphTargetManagers.push(manager.serialize());
  107621. }
  107622. }
  107623. // Lights
  107624. serializationObject.lights = [];
  107625. var index;
  107626. var light;
  107627. for (index = 0; index < scene.lights.length; index++) {
  107628. light = scene.lights[index];
  107629. if (!light.doNotSerialize) {
  107630. serializationObject.lights.push(light.serialize());
  107631. }
  107632. }
  107633. // Cameras
  107634. serializationObject.cameras = [];
  107635. for (index = 0; index < scene.cameras.length; index++) {
  107636. var camera = scene.cameras[index];
  107637. if (!camera.doNotSerialize) {
  107638. serializationObject.cameras.push(camera.serialize());
  107639. }
  107640. }
  107641. if (scene.activeCamera) {
  107642. serializationObject.activeCameraID = scene.activeCamera.id;
  107643. }
  107644. // Animations
  107645. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  107646. // Materials
  107647. serializationObject.materials = [];
  107648. serializationObject.multiMaterials = [];
  107649. var material;
  107650. for (index = 0; index < scene.materials.length; index++) {
  107651. material = scene.materials[index];
  107652. if (!material.doNotSerialize) {
  107653. serializationObject.materials.push(material.serialize());
  107654. }
  107655. }
  107656. // MultiMaterials
  107657. serializationObject.multiMaterials = [];
  107658. for (index = 0; index < scene.multiMaterials.length; index++) {
  107659. var multiMaterial = scene.multiMaterials[index];
  107660. serializationObject.multiMaterials.push(multiMaterial.serialize());
  107661. }
  107662. // Environment texture
  107663. if (scene.environmentTexture) {
  107664. serializationObject.environmentTexture = scene.environmentTexture.name;
  107665. }
  107666. // Skeletons
  107667. serializationObject.skeletons = [];
  107668. for (index = 0; index < scene.skeletons.length; index++) {
  107669. var skeleton = scene.skeletons[index];
  107670. if (!skeleton.doNotSerialize) {
  107671. serializationObject.skeletons.push(skeleton.serialize());
  107672. }
  107673. }
  107674. // Transform nodes
  107675. serializationObject.transformNodes = [];
  107676. for (index = 0; index < scene.transformNodes.length; index++) {
  107677. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  107678. }
  107679. // Geometries
  107680. serializationObject.geometries = {};
  107681. serializationObject.geometries.boxes = [];
  107682. serializationObject.geometries.spheres = [];
  107683. serializationObject.geometries.cylinders = [];
  107684. serializationObject.geometries.toruses = [];
  107685. serializationObject.geometries.grounds = [];
  107686. serializationObject.geometries.planes = [];
  107687. serializationObject.geometries.torusKnots = [];
  107688. serializationObject.geometries.vertexData = [];
  107689. serializedGeometries = [];
  107690. var geometries = scene.getGeometries();
  107691. for (index = 0; index < geometries.length; index++) {
  107692. var geometry = geometries[index];
  107693. if (geometry.isReady()) {
  107694. serializeGeometry(geometry, serializationObject.geometries);
  107695. }
  107696. }
  107697. // Meshes
  107698. serializationObject.meshes = [];
  107699. for (index = 0; index < scene.meshes.length; index++) {
  107700. var abstractMesh = scene.meshes[index];
  107701. if (abstractMesh instanceof BABYLON.Mesh) {
  107702. var mesh = abstractMesh;
  107703. if (!mesh.doNotSerialize) {
  107704. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  107705. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  107706. }
  107707. }
  107708. }
  107709. }
  107710. // Particles Systems
  107711. serializationObject.particleSystems = [];
  107712. for (index = 0; index < scene.particleSystems.length; index++) {
  107713. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  107714. }
  107715. // Action Manager
  107716. if (scene.actionManager) {
  107717. serializationObject.actions = scene.actionManager.serialize("scene");
  107718. }
  107719. // Components
  107720. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  107721. var component = _c[_b];
  107722. component.serialize(serializationObject);
  107723. }
  107724. return serializationObject;
  107725. };
  107726. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  107727. if (withParents === void 0) { withParents = false; }
  107728. if (withChildren === void 0) { withChildren = false; }
  107729. var serializationObject = {};
  107730. SceneSerializer.ClearCache();
  107731. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  107732. if (withParents || withChildren) {
  107733. //deliberate for loop! not for each, appended should be processed as well.
  107734. for (var i = 0; i < toSerialize.length; ++i) {
  107735. if (withChildren) {
  107736. toSerialize[i].getDescendants().forEach(function (node) {
  107737. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  107738. toSerialize.push(node);
  107739. }
  107740. });
  107741. }
  107742. //make sure the array doesn't contain the object already
  107743. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  107744. toSerialize.push(toSerialize[i].parent);
  107745. }
  107746. }
  107747. }
  107748. toSerialize.forEach(function (mesh) {
  107749. finalizeSingleMesh(mesh, serializationObject);
  107750. });
  107751. return serializationObject;
  107752. };
  107753. return SceneSerializer;
  107754. }());
  107755. BABYLON.SceneSerializer = SceneSerializer;
  107756. })(BABYLON || (BABYLON = {}));
  107757. //# sourceMappingURL=babylon.sceneSerializer.js.map
  107758. var BABYLON;
  107759. (function (BABYLON) {
  107760. /**
  107761. * Class used to generate realtime reflection / refraction cube textures
  107762. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  107763. */
  107764. var ReflectionProbe = /** @class */ (function () {
  107765. /**
  107766. * Creates a new reflection probe
  107767. * @param name defines the name of the probe
  107768. * @param size defines the texture resolution (for each face)
  107769. * @param scene defines the hosting scene
  107770. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  107771. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  107772. */
  107773. function ReflectionProbe(
  107774. /** defines the name of the probe */
  107775. name, size, scene, generateMipMaps, useFloat) {
  107776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  107777. if (useFloat === void 0) { useFloat = false; }
  107778. var _this = this;
  107779. this.name = name;
  107780. this._viewMatrix = BABYLON.Matrix.Identity();
  107781. this._target = BABYLON.Vector3.Zero();
  107782. this._add = BABYLON.Vector3.Zero();
  107783. this._invertYAxis = false;
  107784. /** Gets or sets probe position (center of the cube map) */
  107785. this.position = BABYLON.Vector3.Zero();
  107786. this._scene = scene;
  107787. // Create the scene field if not exist.
  107788. if (!this._scene.reflectionProbes) {
  107789. this._scene.reflectionProbes = new Array();
  107790. }
  107791. this._scene.reflectionProbes.push(this);
  107792. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  107793. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  107794. switch (faceIndex) {
  107795. case 0:
  107796. _this._add.copyFromFloats(1, 0, 0);
  107797. break;
  107798. case 1:
  107799. _this._add.copyFromFloats(-1, 0, 0);
  107800. break;
  107801. case 2:
  107802. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  107803. break;
  107804. case 3:
  107805. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  107806. break;
  107807. case 4:
  107808. _this._add.copyFromFloats(0, 0, 1);
  107809. break;
  107810. case 5:
  107811. _this._add.copyFromFloats(0, 0, -1);
  107812. break;
  107813. }
  107814. if (_this._attachedMesh) {
  107815. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  107816. }
  107817. _this.position.addToRef(_this._add, _this._target);
  107818. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  107819. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  107820. scene._forcedViewPosition = _this.position;
  107821. });
  107822. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  107823. scene._forcedViewPosition = null;
  107824. scene.updateTransformMatrix(true);
  107825. });
  107826. if (scene.activeCamera) {
  107827. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  107828. }
  107829. }
  107830. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  107831. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  107832. get: function () {
  107833. return this._renderTargetTexture.samples;
  107834. },
  107835. set: function (value) {
  107836. this._renderTargetTexture.samples = value;
  107837. },
  107838. enumerable: true,
  107839. configurable: true
  107840. });
  107841. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  107842. /** Gets or sets the refresh rate to use (on every frame by default) */
  107843. get: function () {
  107844. return this._renderTargetTexture.refreshRate;
  107845. },
  107846. set: function (value) {
  107847. this._renderTargetTexture.refreshRate = value;
  107848. },
  107849. enumerable: true,
  107850. configurable: true
  107851. });
  107852. /**
  107853. * Gets the hosting scene
  107854. * @returns a Scene
  107855. */
  107856. ReflectionProbe.prototype.getScene = function () {
  107857. return this._scene;
  107858. };
  107859. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  107860. /** Gets the internal CubeTexture used to render to */
  107861. get: function () {
  107862. return this._renderTargetTexture;
  107863. },
  107864. enumerable: true,
  107865. configurable: true
  107866. });
  107867. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  107868. /** Gets the list of meshes to render */
  107869. get: function () {
  107870. return this._renderTargetTexture.renderList;
  107871. },
  107872. enumerable: true,
  107873. configurable: true
  107874. });
  107875. /**
  107876. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  107877. * @param mesh defines the mesh to attach to
  107878. */
  107879. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  107880. this._attachedMesh = mesh;
  107881. };
  107882. /**
  107883. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  107884. * @param renderingGroupId The rendering group id corresponding to its index
  107885. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  107886. */
  107887. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  107888. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  107889. };
  107890. /**
  107891. * Clean all associated resources
  107892. */
  107893. ReflectionProbe.prototype.dispose = function () {
  107894. var index = this._scene.reflectionProbes.indexOf(this);
  107895. if (index !== -1) {
  107896. // Remove from the scene if found
  107897. this._scene.reflectionProbes.splice(index, 1);
  107898. }
  107899. if (this._renderTargetTexture) {
  107900. this._renderTargetTexture.dispose();
  107901. this._renderTargetTexture = null;
  107902. }
  107903. };
  107904. return ReflectionProbe;
  107905. }());
  107906. BABYLON.ReflectionProbe = ReflectionProbe;
  107907. })(BABYLON || (BABYLON = {}));
  107908. //# sourceMappingURL=babylon.reflectionProbe.js.map
  107909. var BABYLON;
  107910. (function (BABYLON) {
  107911. /**
  107912. * Defines the layer scene component responsible to manage any layers
  107913. * in a given scene.
  107914. */
  107915. var LayerSceneComponent = /** @class */ (function () {
  107916. /**
  107917. * Creates a new instance of the component for the given scene
  107918. * @param scene Defines the scene to register the component in
  107919. */
  107920. function LayerSceneComponent(scene) {
  107921. /**
  107922. * The component name helpfull to identify the component in the list of scene components.
  107923. */
  107924. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  107925. this.scene = scene;
  107926. this._engine = scene.getEngine();
  107927. scene.layers = new Array();
  107928. }
  107929. /**
  107930. * Registers the component in a given scene
  107931. */
  107932. LayerSceneComponent.prototype.register = function () {
  107933. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  107934. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  107935. };
  107936. /**
  107937. * Rebuilds the elements related to this component in case of
  107938. * context lost for instance.
  107939. */
  107940. LayerSceneComponent.prototype.rebuild = function () {
  107941. var layers = this.scene.layers;
  107942. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107943. var layer = layers_1[_i];
  107944. layer._rebuild();
  107945. }
  107946. };
  107947. /**
  107948. * Disposes the component and the associated ressources.
  107949. */
  107950. LayerSceneComponent.prototype.dispose = function () {
  107951. var layers = this.scene.layers;
  107952. while (layers.length) {
  107953. layers[0].dispose();
  107954. }
  107955. };
  107956. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  107957. var layers = this.scene.layers;
  107958. if (layers.length) {
  107959. this._engine.setDepthBuffer(false);
  107960. var cameraLayerMask = camera.layerMask;
  107961. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107962. var layer = layers_2[_i];
  107963. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  107964. layer.render();
  107965. }
  107966. }
  107967. this._engine.setDepthBuffer(true);
  107968. }
  107969. };
  107970. LayerSceneComponent.prototype._drawBackground = function (camera) {
  107971. this._draw(camera, true);
  107972. };
  107973. LayerSceneComponent.prototype._drawForeground = function (camera) {
  107974. this._draw(camera, false);
  107975. };
  107976. return LayerSceneComponent;
  107977. }());
  107978. BABYLON.LayerSceneComponent = LayerSceneComponent;
  107979. })(BABYLON || (BABYLON = {}));
  107980. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  107981. var BABYLON;
  107982. (function (BABYLON) {
  107983. /**
  107984. * This represents a full screen 2d layer.
  107985. * This can be usefull to display a picture in the background of your scene for instance.
  107986. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107987. */
  107988. var Layer = /** @class */ (function () {
  107989. /**
  107990. * Instantiates a new layer.
  107991. * This represents a full screen 2d layer.
  107992. * This can be usefull to display a picture in the background of your scene for instance.
  107993. * @see https://www.babylonjs-playground.com/#08A2BS#1
  107994. * @param name Define the name of the layer in the scene
  107995. * @param imgUrl Define the url of the texture to display in the layer
  107996. * @param scene Define the scene the layer belongs to
  107997. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  107998. * @param color Defines a color for the layer
  107999. */
  108000. function Layer(
  108001. /**
  108002. * Define the name of the layer.
  108003. */
  108004. name, imgUrl, scene, isBackground, color) {
  108005. this.name = name;
  108006. /**
  108007. * Define the scale of the layer in order to zoom in out of the texture.
  108008. */
  108009. this.scale = new BABYLON.Vector2(1, 1);
  108010. /**
  108011. * Define an offset for the layer in order to shift the texture.
  108012. */
  108013. this.offset = new BABYLON.Vector2(0, 0);
  108014. /**
  108015. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  108016. */
  108017. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  108018. /**
  108019. * Define a mask to restrict the layer to only some of the scene cameras.
  108020. */
  108021. this.layerMask = 0x0FFFFFFF;
  108022. this._vertexBuffers = {};
  108023. /**
  108024. * An event triggered when the layer is disposed.
  108025. */
  108026. this.onDisposeObservable = new BABYLON.Observable();
  108027. /**
  108028. * An event triggered before rendering the scene
  108029. */
  108030. this.onBeforeRenderObservable = new BABYLON.Observable();
  108031. /**
  108032. * An event triggered after rendering the scene
  108033. */
  108034. this.onAfterRenderObservable = new BABYLON.Observable();
  108035. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  108036. this.isBackground = isBackground === undefined ? true : isBackground;
  108037. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  108038. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  108039. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  108040. if (!layerComponent) {
  108041. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  108042. this._scene._addComponent(layerComponent);
  108043. }
  108044. this._scene.layers.push(this);
  108045. var engine = this._scene.getEngine();
  108046. // VBO
  108047. var vertices = [];
  108048. vertices.push(1, 1);
  108049. vertices.push(-1, 1);
  108050. vertices.push(-1, -1);
  108051. vertices.push(1, -1);
  108052. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108053. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108054. this._createIndexBuffer();
  108055. // Effects
  108056. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  108057. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  108058. }
  108059. Object.defineProperty(Layer.prototype, "onDispose", {
  108060. /**
  108061. * Back compatibility with callback before the onDisposeObservable existed.
  108062. * The set callback will be triggered when the layer has been disposed.
  108063. */
  108064. set: function (callback) {
  108065. if (this._onDisposeObserver) {
  108066. this.onDisposeObservable.remove(this._onDisposeObserver);
  108067. }
  108068. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  108069. },
  108070. enumerable: true,
  108071. configurable: true
  108072. });
  108073. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  108074. /**
  108075. * Back compatibility with callback before the onBeforeRenderObservable existed.
  108076. * The set callback will be triggered just before rendering the layer.
  108077. */
  108078. set: function (callback) {
  108079. if (this._onBeforeRenderObserver) {
  108080. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  108081. }
  108082. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  108083. },
  108084. enumerable: true,
  108085. configurable: true
  108086. });
  108087. Object.defineProperty(Layer.prototype, "onAfterRender", {
  108088. /**
  108089. * Back compatibility with callback before the onAfterRenderObservable existed.
  108090. * The set callback will be triggered just after rendering the layer.
  108091. */
  108092. set: function (callback) {
  108093. if (this._onAfterRenderObserver) {
  108094. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  108095. }
  108096. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  108097. },
  108098. enumerable: true,
  108099. configurable: true
  108100. });
  108101. Layer.prototype._createIndexBuffer = function () {
  108102. var engine = this._scene.getEngine();
  108103. // Indices
  108104. var indices = [];
  108105. indices.push(0);
  108106. indices.push(1);
  108107. indices.push(2);
  108108. indices.push(0);
  108109. indices.push(2);
  108110. indices.push(3);
  108111. this._indexBuffer = engine.createIndexBuffer(indices);
  108112. };
  108113. /** @hidden */
  108114. Layer.prototype._rebuild = function () {
  108115. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108116. if (vb) {
  108117. vb._rebuild();
  108118. }
  108119. this._createIndexBuffer();
  108120. };
  108121. /**
  108122. * Renders the layer in the scene.
  108123. */
  108124. Layer.prototype.render = function () {
  108125. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  108126. // Check
  108127. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  108128. return;
  108129. var engine = this._scene.getEngine();
  108130. this.onBeforeRenderObservable.notifyObservers(this);
  108131. // Render
  108132. engine.enableEffect(currentEffect);
  108133. engine.setState(false);
  108134. // Texture
  108135. currentEffect.setTexture("textureSampler", this.texture);
  108136. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  108137. // Color
  108138. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  108139. // Scale / offset
  108140. currentEffect.setVector2("offset", this.offset);
  108141. currentEffect.setVector2("scale", this.scale);
  108142. // VBOs
  108143. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  108144. // Draw order
  108145. if (!this.alphaTest) {
  108146. engine.setAlphaMode(this.alphaBlendingMode);
  108147. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108148. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108149. }
  108150. else {
  108151. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108152. }
  108153. this.onAfterRenderObservable.notifyObservers(this);
  108154. };
  108155. /**
  108156. * Disposes and releases the associated ressources.
  108157. */
  108158. Layer.prototype.dispose = function () {
  108159. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  108160. if (vertexBuffer) {
  108161. vertexBuffer.dispose();
  108162. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  108163. }
  108164. if (this._indexBuffer) {
  108165. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  108166. this._indexBuffer = null;
  108167. }
  108168. if (this.texture) {
  108169. this.texture.dispose();
  108170. this.texture = null;
  108171. }
  108172. // Remove from scene
  108173. var index = this._scene.layers.indexOf(this);
  108174. this._scene.layers.splice(index, 1);
  108175. // Callback
  108176. this.onDisposeObservable.notifyObservers(this);
  108177. this.onDisposeObservable.clear();
  108178. this.onAfterRenderObservable.clear();
  108179. this.onBeforeRenderObservable.clear();
  108180. };
  108181. return Layer;
  108182. }());
  108183. BABYLON.Layer = Layer;
  108184. })(BABYLON || (BABYLON = {}));
  108185. //# sourceMappingURL=babylon.layer.js.map
  108186. var BABYLON;
  108187. (function (BABYLON) {
  108188. var TextureTools = /** @class */ (function () {
  108189. function TextureTools() {
  108190. }
  108191. /**
  108192. * Uses the GPU to create a copy texture rescaled at a given size
  108193. * @param texture Texture to copy from
  108194. * @param width Desired width
  108195. * @param height Desired height
  108196. * @return Generated texture
  108197. */
  108198. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  108199. if (useBilinearMode === void 0) { useBilinearMode = true; }
  108200. var scene = texture.getScene();
  108201. var engine = scene.getEngine();
  108202. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  108203. rtt.wrapU = texture.wrapU;
  108204. rtt.wrapV = texture.wrapV;
  108205. rtt.uOffset = texture.uOffset;
  108206. rtt.vOffset = texture.vOffset;
  108207. rtt.uScale = texture.uScale;
  108208. rtt.vScale = texture.vScale;
  108209. rtt.uAng = texture.uAng;
  108210. rtt.vAng = texture.vAng;
  108211. rtt.wAng = texture.wAng;
  108212. rtt.coordinatesIndex = texture.coordinatesIndex;
  108213. rtt.level = texture.level;
  108214. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  108215. rtt._texture.isReady = false;
  108216. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108217. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108218. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108219. passPostProcess.getEffect().executeWhenCompiled(function () {
  108220. passPostProcess.onApply = function (effect) {
  108221. effect.setTexture("textureSampler", texture);
  108222. };
  108223. var internalTexture = rtt.getInternalTexture();
  108224. if (internalTexture) {
  108225. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  108226. engine.unBindFramebuffer(internalTexture);
  108227. rtt.disposeFramebufferObjects();
  108228. passPostProcess.dispose();
  108229. internalTexture.isReady = true;
  108230. }
  108231. });
  108232. return rtt;
  108233. };
  108234. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  108235. if (!scene._environmentBRDFTexture) {
  108236. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108237. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108238. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108239. scene._environmentBRDFTexture = texture;
  108240. }
  108241. return scene._environmentBRDFTexture;
  108242. };
  108243. 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=";
  108244. return TextureTools;
  108245. }());
  108246. BABYLON.TextureTools = TextureTools;
  108247. })(BABYLON || (BABYLON = {}));
  108248. //# sourceMappingURL=babylon.textureTools.js.map
  108249. var BABYLON;
  108250. (function (BABYLON) {
  108251. /**
  108252. * 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.
  108253. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  108254. */
  108255. var FramingBehavior = /** @class */ (function () {
  108256. function FramingBehavior() {
  108257. this._mode = FramingBehavior.FitFrustumSidesMode;
  108258. this._radiusScale = 1.0;
  108259. this._positionScale = 0.5;
  108260. this._defaultElevation = 0.3;
  108261. this._elevationReturnTime = 1500;
  108262. this._elevationReturnWaitTime = 1000;
  108263. this._zoomStopsAnimation = false;
  108264. this._framingTime = 1500;
  108265. /**
  108266. * Define if the behavior should automatically change the configured
  108267. * camera limits and sensibilities.
  108268. */
  108269. this.autoCorrectCameraLimitsAndSensibility = true;
  108270. this._isPointerDown = false;
  108271. this._lastInteractionTime = -Infinity;
  108272. // Framing control
  108273. this._animatables = new Array();
  108274. this._betaIsAnimating = false;
  108275. }
  108276. Object.defineProperty(FramingBehavior.prototype, "name", {
  108277. /**
  108278. * Gets the name of the behavior.
  108279. */
  108280. get: function () {
  108281. return "Framing";
  108282. },
  108283. enumerable: true,
  108284. configurable: true
  108285. });
  108286. Object.defineProperty(FramingBehavior.prototype, "mode", {
  108287. /**
  108288. * Gets current mode used by the behavior.
  108289. */
  108290. get: function () {
  108291. return this._mode;
  108292. },
  108293. /**
  108294. * Sets the current mode used by the behavior
  108295. */
  108296. set: function (mode) {
  108297. this._mode = mode;
  108298. },
  108299. enumerable: true,
  108300. configurable: true
  108301. });
  108302. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  108303. /**
  108304. * Gets the scale applied to the radius
  108305. */
  108306. get: function () {
  108307. return this._radiusScale;
  108308. },
  108309. /**
  108310. * Sets the scale applied to the radius (1 by default)
  108311. */
  108312. set: function (radius) {
  108313. this._radiusScale = radius;
  108314. },
  108315. enumerable: true,
  108316. configurable: true
  108317. });
  108318. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  108319. /**
  108320. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108321. */
  108322. get: function () {
  108323. return this._positionScale;
  108324. },
  108325. /**
  108326. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  108327. */
  108328. set: function (scale) {
  108329. this._positionScale = scale;
  108330. },
  108331. enumerable: true,
  108332. configurable: true
  108333. });
  108334. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  108335. /**
  108336. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108337. * behaviour is triggered, in radians.
  108338. */
  108339. get: function () {
  108340. return this._defaultElevation;
  108341. },
  108342. /**
  108343. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  108344. * behaviour is triggered, in radians.
  108345. */
  108346. set: function (elevation) {
  108347. this._defaultElevation = elevation;
  108348. },
  108349. enumerable: true,
  108350. configurable: true
  108351. });
  108352. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  108353. /**
  108354. * Gets the time (in milliseconds) taken to return to the default beta position.
  108355. * Negative value indicates camera should not return to default.
  108356. */
  108357. get: function () {
  108358. return this._elevationReturnTime;
  108359. },
  108360. /**
  108361. * Sets the time (in milliseconds) taken to return to the default beta position.
  108362. * Negative value indicates camera should not return to default.
  108363. */
  108364. set: function (speed) {
  108365. this._elevationReturnTime = speed;
  108366. },
  108367. enumerable: true,
  108368. configurable: true
  108369. });
  108370. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  108371. /**
  108372. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108373. */
  108374. get: function () {
  108375. return this._elevationReturnWaitTime;
  108376. },
  108377. /**
  108378. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  108379. */
  108380. set: function (time) {
  108381. this._elevationReturnWaitTime = time;
  108382. },
  108383. enumerable: true,
  108384. configurable: true
  108385. });
  108386. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  108387. /**
  108388. * Gets the flag that indicates if user zooming should stop animation.
  108389. */
  108390. get: function () {
  108391. return this._zoomStopsAnimation;
  108392. },
  108393. /**
  108394. * Sets the flag that indicates if user zooming should stop animation.
  108395. */
  108396. set: function (flag) {
  108397. this._zoomStopsAnimation = flag;
  108398. },
  108399. enumerable: true,
  108400. configurable: true
  108401. });
  108402. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  108403. /**
  108404. * Gets the transition time when framing the mesh, in milliseconds
  108405. */
  108406. get: function () {
  108407. return this._framingTime;
  108408. },
  108409. /**
  108410. * Sets the transition time when framing the mesh, in milliseconds
  108411. */
  108412. set: function (time) {
  108413. this._framingTime = time;
  108414. },
  108415. enumerable: true,
  108416. configurable: true
  108417. });
  108418. /**
  108419. * Initializes the behavior.
  108420. */
  108421. FramingBehavior.prototype.init = function () {
  108422. // Do notihng
  108423. };
  108424. /**
  108425. * Attaches the behavior to its arc rotate camera.
  108426. * @param camera Defines the camera to attach the behavior to
  108427. */
  108428. FramingBehavior.prototype.attach = function (camera) {
  108429. var _this = this;
  108430. this._attachedCamera = camera;
  108431. var scene = this._attachedCamera.getScene();
  108432. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  108433. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  108434. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  108435. _this._isPointerDown = true;
  108436. return;
  108437. }
  108438. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  108439. _this._isPointerDown = false;
  108440. }
  108441. });
  108442. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108443. if (mesh) {
  108444. _this.zoomOnMesh(mesh);
  108445. }
  108446. });
  108447. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108448. // Stop the animation if there is user interaction and the animation should stop for this interaction
  108449. _this._applyUserInteraction();
  108450. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  108451. // back to the default position after a given timeout
  108452. _this._maintainCameraAboveGround();
  108453. });
  108454. };
  108455. /**
  108456. * Detaches the behavior from its current arc rotate camera.
  108457. */
  108458. FramingBehavior.prototype.detach = function () {
  108459. if (!this._attachedCamera) {
  108460. return;
  108461. }
  108462. var scene = this._attachedCamera.getScene();
  108463. if (this._onPrePointerObservableObserver) {
  108464. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  108465. }
  108466. if (this._onAfterCheckInputsObserver) {
  108467. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108468. }
  108469. if (this._onMeshTargetChangedObserver) {
  108470. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108471. }
  108472. this._attachedCamera = null;
  108473. };
  108474. /**
  108475. * Targets the given mesh and updates zoom level accordingly.
  108476. * @param mesh The mesh to target.
  108477. * @param radius Optional. If a cached radius position already exists, overrides default.
  108478. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108479. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108480. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108481. */
  108482. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108483. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108484. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108485. mesh.computeWorldMatrix(true);
  108486. var boundingBox = mesh.getBoundingInfo().boundingBox;
  108487. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  108488. };
  108489. /**
  108490. * Targets the given mesh with its children and updates zoom level accordingly.
  108491. * @param mesh The mesh to target.
  108492. * @param radius Optional. If a cached radius position already exists, overrides default.
  108493. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108494. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108495. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108496. */
  108497. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  108498. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108499. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108500. mesh.computeWorldMatrix(true);
  108501. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  108502. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  108503. };
  108504. /**
  108505. * Targets the given meshes with their children and updates zoom level accordingly.
  108506. * @param meshes The mesh to target.
  108507. * @param radius Optional. If a cached radius position already exists, overrides default.
  108508. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  108509. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108510. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108511. */
  108512. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  108513. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108514. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108515. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  108516. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  108517. for (var i = 0; i < meshes.length; i++) {
  108518. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  108519. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  108520. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  108521. }
  108522. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  108523. };
  108524. /**
  108525. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  108526. * @param minimumWorld Determines the smaller position of the bounding box extend
  108527. * @param maximumWorld Determines the bigger position of the bounding box extend
  108528. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  108529. * @param onAnimationEnd Callback triggered at the end of the framing animation
  108530. */
  108531. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  108532. var _this = this;
  108533. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  108534. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  108535. var zoomTarget;
  108536. if (!this._attachedCamera) {
  108537. return;
  108538. }
  108539. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  108540. var bottom = minimumWorld.y;
  108541. var top = maximumWorld.y;
  108542. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  108543. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  108544. if (focusOnOriginXZ) {
  108545. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  108546. }
  108547. else {
  108548. var centerWorld = minimumWorld.add(radiusWorld);
  108549. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  108550. }
  108551. if (!this._vectorTransition) {
  108552. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  108553. }
  108554. this._betaIsAnimating = true;
  108555. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  108556. if (animatable) {
  108557. this._animatables.push(animatable);
  108558. }
  108559. // sets the radius and lower radius bounds
  108560. // Small delta ensures camera is not always at lower zoom limit.
  108561. var radius = 0;
  108562. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  108563. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108564. if (this.autoCorrectCameraLimitsAndSensibility) {
  108565. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  108566. }
  108567. radius = position;
  108568. }
  108569. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108570. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  108571. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  108572. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  108573. }
  108574. }
  108575. // Set sensibilities
  108576. if (this.autoCorrectCameraLimitsAndSensibility) {
  108577. var extend = maximumWorld.subtract(minimumWorld).length();
  108578. this._attachedCamera.panningSensibility = 5000 / extend;
  108579. this._attachedCamera.wheelPrecision = 100 / radius;
  108580. }
  108581. // transition to new radius
  108582. if (!this._radiusTransition) {
  108583. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108584. }
  108585. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  108586. _this.stopAllAnimations();
  108587. if (onAnimationEnd) {
  108588. onAnimationEnd();
  108589. }
  108590. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  108591. _this._attachedCamera.storeState();
  108592. }
  108593. });
  108594. if (animatable) {
  108595. this._animatables.push(animatable);
  108596. }
  108597. };
  108598. /**
  108599. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  108600. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  108601. * frustum width.
  108602. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  108603. * to fully enclose the mesh in the viewing frustum.
  108604. */
  108605. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  108606. var size = maximumWorld.subtract(minimumWorld);
  108607. var boxVectorGlobalDiagonal = size.length();
  108608. var frustumSlope = this._getFrustumSlope();
  108609. // Formula for setting distance
  108610. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  108611. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  108612. // Horizon distance
  108613. var radius = radiusWithoutFraming * this._radiusScale;
  108614. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  108615. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  108616. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  108617. var camera = this._attachedCamera;
  108618. if (!camera) {
  108619. return 0;
  108620. }
  108621. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  108622. // Don't exceed the requested limit
  108623. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  108624. }
  108625. // Don't exceed the upper radius limit
  108626. if (camera.upperRadiusLimit) {
  108627. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  108628. }
  108629. return distance;
  108630. };
  108631. /**
  108632. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  108633. * is automatically returned to its default position (expected to be above ground plane).
  108634. */
  108635. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  108636. var _this = this;
  108637. if (this._elevationReturnTime < 0) {
  108638. return;
  108639. }
  108640. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  108641. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  108642. var limitBeta = Math.PI * 0.5;
  108643. // Bring the camera back up if below the ground plane
  108644. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  108645. this._betaIsAnimating = true;
  108646. //Transition to new position
  108647. this.stopAllAnimations();
  108648. if (!this._betaTransition) {
  108649. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  108650. }
  108651. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  108652. _this._clearAnimationLocks();
  108653. _this.stopAllAnimations();
  108654. });
  108655. if (animatabe) {
  108656. this._animatables.push(animatabe);
  108657. }
  108658. }
  108659. };
  108660. /**
  108661. * Returns the frustum slope based on the canvas ratio and camera FOV
  108662. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  108663. */
  108664. FramingBehavior.prototype._getFrustumSlope = function () {
  108665. // Calculate the viewport ratio
  108666. // Aspect Ratio is Height/Width.
  108667. var camera = this._attachedCamera;
  108668. if (!camera) {
  108669. return BABYLON.Vector2.Zero();
  108670. }
  108671. var engine = camera.getScene().getEngine();
  108672. var aspectRatio = engine.getAspectRatio(camera);
  108673. // Camera FOV is the vertical field of view (top-bottom) in radians.
  108674. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  108675. var frustumSlopeY = Math.tan(camera.fov / 2);
  108676. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  108677. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  108678. // along the forward vector.
  108679. var frustumSlopeX = frustumSlopeY * aspectRatio;
  108680. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  108681. };
  108682. /**
  108683. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  108684. */
  108685. FramingBehavior.prototype._clearAnimationLocks = function () {
  108686. this._betaIsAnimating = false;
  108687. };
  108688. /**
  108689. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  108690. */
  108691. FramingBehavior.prototype._applyUserInteraction = function () {
  108692. if (this.isUserIsMoving) {
  108693. this._lastInteractionTime = BABYLON.Tools.Now;
  108694. this.stopAllAnimations();
  108695. this._clearAnimationLocks();
  108696. }
  108697. };
  108698. /**
  108699. * Stops and removes all animations that have been applied to the camera
  108700. */
  108701. FramingBehavior.prototype.stopAllAnimations = function () {
  108702. if (this._attachedCamera) {
  108703. this._attachedCamera.animations = [];
  108704. }
  108705. while (this._animatables.length) {
  108706. if (this._animatables[0]) {
  108707. this._animatables[0].onAnimationEnd = null;
  108708. this._animatables[0].stop();
  108709. }
  108710. this._animatables.shift();
  108711. }
  108712. };
  108713. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  108714. /**
  108715. * Gets a value indicating if the user is moving the camera
  108716. */
  108717. get: function () {
  108718. if (!this._attachedCamera) {
  108719. return false;
  108720. }
  108721. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  108722. this._attachedCamera.inertialBetaOffset !== 0 ||
  108723. this._attachedCamera.inertialRadiusOffset !== 0 ||
  108724. this._attachedCamera.inertialPanningX !== 0 ||
  108725. this._attachedCamera.inertialPanningY !== 0 ||
  108726. this._isPointerDown;
  108727. },
  108728. enumerable: true,
  108729. configurable: true
  108730. });
  108731. /**
  108732. * The easing function used by animations
  108733. */
  108734. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  108735. /**
  108736. * The easing mode used by animations
  108737. */
  108738. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  108739. // Statics
  108740. /**
  108741. * The camera can move all the way towards the mesh.
  108742. */
  108743. FramingBehavior.IgnoreBoundsSizeMode = 0;
  108744. /**
  108745. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  108746. */
  108747. FramingBehavior.FitFrustumSidesMode = 1;
  108748. return FramingBehavior;
  108749. }());
  108750. BABYLON.FramingBehavior = FramingBehavior;
  108751. })(BABYLON || (BABYLON = {}));
  108752. //# sourceMappingURL=babylon.framingBehavior.js.map
  108753. var BABYLON;
  108754. (function (BABYLON) {
  108755. /**
  108756. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  108757. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  108758. */
  108759. var BouncingBehavior = /** @class */ (function () {
  108760. function BouncingBehavior() {
  108761. /**
  108762. * The duration of the animation, in milliseconds
  108763. */
  108764. this.transitionDuration = 450;
  108765. /**
  108766. * Length of the distance animated by the transition when lower radius is reached
  108767. */
  108768. this.lowerRadiusTransitionRange = 2;
  108769. /**
  108770. * Length of the distance animated by the transition when upper radius is reached
  108771. */
  108772. this.upperRadiusTransitionRange = -2;
  108773. this._autoTransitionRange = false;
  108774. // Animations
  108775. this._radiusIsAnimating = false;
  108776. this._radiusBounceTransition = null;
  108777. this._animatables = new Array();
  108778. }
  108779. Object.defineProperty(BouncingBehavior.prototype, "name", {
  108780. /**
  108781. * Gets the name of the behavior.
  108782. */
  108783. get: function () {
  108784. return "Bouncing";
  108785. },
  108786. enumerable: true,
  108787. configurable: true
  108788. });
  108789. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  108790. /**
  108791. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108792. */
  108793. get: function () {
  108794. return this._autoTransitionRange;
  108795. },
  108796. /**
  108797. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  108798. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  108799. */
  108800. set: function (value) {
  108801. var _this = this;
  108802. if (this._autoTransitionRange === value) {
  108803. return;
  108804. }
  108805. this._autoTransitionRange = value;
  108806. var camera = this._attachedCamera;
  108807. if (!camera) {
  108808. return;
  108809. }
  108810. if (value) {
  108811. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  108812. if (!mesh) {
  108813. return;
  108814. }
  108815. mesh.computeWorldMatrix(true);
  108816. var diagonal = mesh.getBoundingInfo().diagonalLength;
  108817. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  108818. _this.upperRadiusTransitionRange = diagonal * 0.05;
  108819. });
  108820. }
  108821. else if (this._onMeshTargetChangedObserver) {
  108822. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108823. }
  108824. },
  108825. enumerable: true,
  108826. configurable: true
  108827. });
  108828. /**
  108829. * Initializes the behavior.
  108830. */
  108831. BouncingBehavior.prototype.init = function () {
  108832. // Do notihng
  108833. };
  108834. /**
  108835. * Attaches the behavior to its arc rotate camera.
  108836. * @param camera Defines the camera to attach the behavior to
  108837. */
  108838. BouncingBehavior.prototype.attach = function (camera) {
  108839. var _this = this;
  108840. this._attachedCamera = camera;
  108841. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  108842. if (!_this._attachedCamera) {
  108843. return;
  108844. }
  108845. // Add the bounce animation to the lower radius limit
  108846. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  108847. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  108848. }
  108849. // Add the bounce animation to the upper radius limit
  108850. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  108851. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  108852. }
  108853. });
  108854. };
  108855. /**
  108856. * Detaches the behavior from its current arc rotate camera.
  108857. */
  108858. BouncingBehavior.prototype.detach = function () {
  108859. if (!this._attachedCamera) {
  108860. return;
  108861. }
  108862. if (this._onAfterCheckInputsObserver) {
  108863. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  108864. }
  108865. if (this._onMeshTargetChangedObserver) {
  108866. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  108867. }
  108868. this._attachedCamera = null;
  108869. };
  108870. /**
  108871. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  108872. * @param radiusLimit The limit to check against.
  108873. * @return Bool to indicate if at limit.
  108874. */
  108875. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  108876. if (!this._attachedCamera) {
  108877. return false;
  108878. }
  108879. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  108880. return true;
  108881. }
  108882. return false;
  108883. };
  108884. /**
  108885. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  108886. * @param radiusDelta The delta by which to animate to. Can be negative.
  108887. */
  108888. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  108889. var _this = this;
  108890. if (!this._attachedCamera) {
  108891. return;
  108892. }
  108893. if (!this._radiusBounceTransition) {
  108894. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  108895. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  108896. }
  108897. // Prevent zoom until bounce has completed
  108898. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  108899. this._attachedCamera.wheelPrecision = Infinity;
  108900. this._attachedCamera.inertialRadiusOffset = 0;
  108901. // Animate to the radius limit
  108902. this.stopAllAnimations();
  108903. this._radiusIsAnimating = true;
  108904. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  108905. if (animatable) {
  108906. this._animatables.push(animatable);
  108907. }
  108908. };
  108909. /**
  108910. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  108911. */
  108912. BouncingBehavior.prototype._clearAnimationLocks = function () {
  108913. this._radiusIsAnimating = false;
  108914. if (this._attachedCamera) {
  108915. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  108916. }
  108917. };
  108918. /**
  108919. * Stops and removes all animations that have been applied to the camera
  108920. */
  108921. BouncingBehavior.prototype.stopAllAnimations = function () {
  108922. if (this._attachedCamera) {
  108923. this._attachedCamera.animations = [];
  108924. }
  108925. while (this._animatables.length) {
  108926. this._animatables[0].onAnimationEnd = null;
  108927. this._animatables[0].stop();
  108928. this._animatables.shift();
  108929. }
  108930. };
  108931. /**
  108932. * The easing function used by animations
  108933. */
  108934. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  108935. /**
  108936. * The easing mode used by animations
  108937. */
  108938. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  108939. return BouncingBehavior;
  108940. }());
  108941. BABYLON.BouncingBehavior = BouncingBehavior;
  108942. })(BABYLON || (BABYLON = {}));
  108943. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  108944. var BABYLON;
  108945. (function (BABYLON) {
  108946. /**
  108947. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  108948. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  108949. */
  108950. var AutoRotationBehavior = /** @class */ (function () {
  108951. function AutoRotationBehavior() {
  108952. this._zoomStopsAnimation = false;
  108953. this._idleRotationSpeed = 0.05;
  108954. this._idleRotationWaitTime = 2000;
  108955. this._idleRotationSpinupTime = 2000;
  108956. this._isPointerDown = false;
  108957. this._lastFrameTime = null;
  108958. this._lastInteractionTime = -Infinity;
  108959. this._cameraRotationSpeed = 0;
  108960. this._lastFrameRadius = 0;
  108961. }
  108962. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  108963. /**
  108964. * Gets the name of the behavior.
  108965. */
  108966. get: function () {
  108967. return "AutoRotation";
  108968. },
  108969. enumerable: true,
  108970. configurable: true
  108971. });
  108972. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  108973. /**
  108974. * Gets the flag that indicates if user zooming should stop animation.
  108975. */
  108976. get: function () {
  108977. return this._zoomStopsAnimation;
  108978. },
  108979. /**
  108980. * Sets the flag that indicates if user zooming should stop animation.
  108981. */
  108982. set: function (flag) {
  108983. this._zoomStopsAnimation = flag;
  108984. },
  108985. enumerable: true,
  108986. configurable: true
  108987. });
  108988. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  108989. /**
  108990. * Gets the default speed at which the camera rotates around the model.
  108991. */
  108992. get: function () {
  108993. return this._idleRotationSpeed;
  108994. },
  108995. /**
  108996. * Sets the default speed at which the camera rotates around the model.
  108997. */
  108998. set: function (speed) {
  108999. this._idleRotationSpeed = speed;
  109000. },
  109001. enumerable: true,
  109002. configurable: true
  109003. });
  109004. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  109005. /**
  109006. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  109007. */
  109008. get: function () {
  109009. return this._idleRotationWaitTime;
  109010. },
  109011. /**
  109012. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  109013. */
  109014. set: function (time) {
  109015. this._idleRotationWaitTime = time;
  109016. },
  109017. enumerable: true,
  109018. configurable: true
  109019. });
  109020. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  109021. /**
  109022. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109023. */
  109024. get: function () {
  109025. return this._idleRotationSpinupTime;
  109026. },
  109027. /**
  109028. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  109029. */
  109030. set: function (time) {
  109031. this._idleRotationSpinupTime = time;
  109032. },
  109033. enumerable: true,
  109034. configurable: true
  109035. });
  109036. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  109037. /**
  109038. * Gets a value indicating if the camera is currently rotating because of this behavior
  109039. */
  109040. get: function () {
  109041. return Math.abs(this._cameraRotationSpeed) > 0;
  109042. },
  109043. enumerable: true,
  109044. configurable: true
  109045. });
  109046. /**
  109047. * Initializes the behavior.
  109048. */
  109049. AutoRotationBehavior.prototype.init = function () {
  109050. // Do notihng
  109051. };
  109052. /**
  109053. * Attaches the behavior to its arc rotate camera.
  109054. * @param camera Defines the camera to attach the behavior to
  109055. */
  109056. AutoRotationBehavior.prototype.attach = function (camera) {
  109057. var _this = this;
  109058. this._attachedCamera = camera;
  109059. var scene = this._attachedCamera.getScene();
  109060. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  109061. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  109062. _this._isPointerDown = true;
  109063. return;
  109064. }
  109065. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  109066. _this._isPointerDown = false;
  109067. }
  109068. });
  109069. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  109070. var now = BABYLON.Tools.Now;
  109071. var dt = 0;
  109072. if (_this._lastFrameTime != null) {
  109073. dt = now - _this._lastFrameTime;
  109074. }
  109075. _this._lastFrameTime = now;
  109076. // Stop the animation if there is user interaction and the animation should stop for this interaction
  109077. _this._applyUserInteraction();
  109078. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  109079. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  109080. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  109081. // Step camera rotation by rotation speed
  109082. if (_this._attachedCamera) {
  109083. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  109084. }
  109085. });
  109086. };
  109087. /**
  109088. * Detaches the behavior from its current arc rotate camera.
  109089. */
  109090. AutoRotationBehavior.prototype.detach = function () {
  109091. if (!this._attachedCamera) {
  109092. return;
  109093. }
  109094. var scene = this._attachedCamera.getScene();
  109095. if (this._onPrePointerObservableObserver) {
  109096. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  109097. }
  109098. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  109099. this._attachedCamera = null;
  109100. };
  109101. /**
  109102. * Returns true if user is scrolling.
  109103. * @return true if user is scrolling.
  109104. */
  109105. AutoRotationBehavior.prototype._userIsZooming = function () {
  109106. if (!this._attachedCamera) {
  109107. return false;
  109108. }
  109109. return this._attachedCamera.inertialRadiusOffset !== 0;
  109110. };
  109111. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  109112. if (!this._attachedCamera) {
  109113. return false;
  109114. }
  109115. var zoomHasHitLimit = false;
  109116. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  109117. zoomHasHitLimit = true;
  109118. }
  109119. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  109120. this._lastFrameRadius = this._attachedCamera.radius;
  109121. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  109122. };
  109123. /**
  109124. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  109125. */
  109126. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  109127. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  109128. this._lastInteractionTime = BABYLON.Tools.Now;
  109129. }
  109130. };
  109131. // Tools
  109132. AutoRotationBehavior.prototype._userIsMoving = function () {
  109133. if (!this._attachedCamera) {
  109134. return false;
  109135. }
  109136. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  109137. this._attachedCamera.inertialBetaOffset !== 0 ||
  109138. this._attachedCamera.inertialRadiusOffset !== 0 ||
  109139. this._attachedCamera.inertialPanningX !== 0 ||
  109140. this._attachedCamera.inertialPanningY !== 0 ||
  109141. this._isPointerDown;
  109142. };
  109143. return AutoRotationBehavior;
  109144. }());
  109145. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  109146. })(BABYLON || (BABYLON = {}));
  109147. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  109148. var BABYLON;
  109149. (function (BABYLON) {
  109150. var NullEngineOptions = /** @class */ (function () {
  109151. function NullEngineOptions() {
  109152. this.renderWidth = 512;
  109153. this.renderHeight = 256;
  109154. this.textureSize = 512;
  109155. this.deterministicLockstep = false;
  109156. this.lockstepMaxSteps = 4;
  109157. }
  109158. return NullEngineOptions;
  109159. }());
  109160. BABYLON.NullEngineOptions = NullEngineOptions;
  109161. /**
  109162. * The null engine class provides support for headless version of babylon.js.
  109163. * This can be used in server side scenario or for testing purposes
  109164. */
  109165. var NullEngine = /** @class */ (function (_super) {
  109166. __extends(NullEngine, _super);
  109167. function NullEngine(options) {
  109168. if (options === void 0) { options = new NullEngineOptions(); }
  109169. var _this = _super.call(this, null) || this;
  109170. if (options.deterministicLockstep === undefined) {
  109171. options.deterministicLockstep = false;
  109172. }
  109173. if (options.lockstepMaxSteps === undefined) {
  109174. options.lockstepMaxSteps = 4;
  109175. }
  109176. _this._options = options;
  109177. // Init caps
  109178. // We consider we are on a webgl1 capable device
  109179. _this._caps = new BABYLON.EngineCapabilities();
  109180. _this._caps.maxTexturesImageUnits = 16;
  109181. _this._caps.maxVertexTextureImageUnits = 16;
  109182. _this._caps.maxTextureSize = 512;
  109183. _this._caps.maxCubemapTextureSize = 512;
  109184. _this._caps.maxRenderTextureSize = 512;
  109185. _this._caps.maxVertexAttribs = 16;
  109186. _this._caps.maxVaryingVectors = 16;
  109187. _this._caps.maxFragmentUniformVectors = 16;
  109188. _this._caps.maxVertexUniformVectors = 16;
  109189. // Extensions
  109190. _this._caps.standardDerivatives = false;
  109191. _this._caps.astc = null;
  109192. _this._caps.s3tc = null;
  109193. _this._caps.pvrtc = null;
  109194. _this._caps.etc1 = null;
  109195. _this._caps.etc2 = null;
  109196. _this._caps.textureAnisotropicFilterExtension = null;
  109197. _this._caps.maxAnisotropy = 0;
  109198. _this._caps.uintIndices = false;
  109199. _this._caps.fragmentDepthSupported = false;
  109200. _this._caps.highPrecisionShaderSupported = true;
  109201. _this._caps.colorBufferFloat = false;
  109202. _this._caps.textureFloat = false;
  109203. _this._caps.textureFloatLinearFiltering = false;
  109204. _this._caps.textureFloatRender = false;
  109205. _this._caps.textureHalfFloat = false;
  109206. _this._caps.textureHalfFloatLinearFiltering = false;
  109207. _this._caps.textureHalfFloatRender = false;
  109208. _this._caps.textureLOD = false;
  109209. _this._caps.drawBuffersExtension = false;
  109210. _this._caps.depthTextureExtension = false;
  109211. _this._caps.vertexArrayObject = false;
  109212. _this._caps.instancedArrays = false;
  109213. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  109214. // Wrappers
  109215. if (typeof URL === "undefined") {
  109216. URL = {
  109217. createObjectURL: function () { },
  109218. revokeObjectURL: function () { }
  109219. };
  109220. }
  109221. if (typeof Blob === "undefined") {
  109222. Blob = function () { };
  109223. }
  109224. return _this;
  109225. }
  109226. NullEngine.prototype.isDeterministicLockStep = function () {
  109227. return this._options.deterministicLockstep;
  109228. };
  109229. NullEngine.prototype.getLockstepMaxSteps = function () {
  109230. return this._options.lockstepMaxSteps;
  109231. };
  109232. NullEngine.prototype.getHardwareScalingLevel = function () {
  109233. return 1.0;
  109234. };
  109235. NullEngine.prototype.createVertexBuffer = function (vertices) {
  109236. return {
  109237. capacity: 0,
  109238. references: 1,
  109239. is32Bits: false
  109240. };
  109241. };
  109242. NullEngine.prototype.createIndexBuffer = function (indices) {
  109243. return {
  109244. capacity: 0,
  109245. references: 1,
  109246. is32Bits: false
  109247. };
  109248. };
  109249. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  109250. if (stencil === void 0) { stencil = false; }
  109251. };
  109252. NullEngine.prototype.getRenderWidth = function (useScreen) {
  109253. if (useScreen === void 0) { useScreen = false; }
  109254. if (!useScreen && this._currentRenderTarget) {
  109255. return this._currentRenderTarget.width;
  109256. }
  109257. return this._options.renderWidth;
  109258. };
  109259. NullEngine.prototype.getRenderHeight = function (useScreen) {
  109260. if (useScreen === void 0) { useScreen = false; }
  109261. if (!useScreen && this._currentRenderTarget) {
  109262. return this._currentRenderTarget.height;
  109263. }
  109264. return this._options.renderHeight;
  109265. };
  109266. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  109267. this._cachedViewport = viewport;
  109268. };
  109269. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  109270. return {
  109271. transformFeedback: null,
  109272. __SPECTOR_rebuildProgram: null
  109273. };
  109274. };
  109275. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  109276. return [];
  109277. };
  109278. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  109279. return [];
  109280. };
  109281. NullEngine.prototype.bindSamplers = function (effect) {
  109282. this._currentEffect = null;
  109283. };
  109284. NullEngine.prototype.enableEffect = function (effect) {
  109285. this._currentEffect = effect;
  109286. if (effect.onBind) {
  109287. effect.onBind(effect);
  109288. }
  109289. if (effect._onBindObservable) {
  109290. effect._onBindObservable.notifyObservers(effect);
  109291. }
  109292. };
  109293. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  109294. if (zOffset === void 0) { zOffset = 0; }
  109295. if (reverseSide === void 0) { reverseSide = false; }
  109296. };
  109297. NullEngine.prototype.setIntArray = function (uniform, array) {
  109298. };
  109299. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  109300. };
  109301. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  109302. };
  109303. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  109304. };
  109305. NullEngine.prototype.setFloatArray = function (uniform, array) {
  109306. };
  109307. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  109308. };
  109309. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  109310. };
  109311. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  109312. };
  109313. NullEngine.prototype.setArray = function (uniform, array) {
  109314. };
  109315. NullEngine.prototype.setArray2 = function (uniform, array) {
  109316. };
  109317. NullEngine.prototype.setArray3 = function (uniform, array) {
  109318. };
  109319. NullEngine.prototype.setArray4 = function (uniform, array) {
  109320. };
  109321. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  109322. };
  109323. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  109324. };
  109325. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  109326. };
  109327. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  109328. };
  109329. NullEngine.prototype.setFloat = function (uniform, value) {
  109330. };
  109331. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  109332. };
  109333. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  109334. };
  109335. NullEngine.prototype.setBool = function (uniform, bool) {
  109336. };
  109337. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  109338. };
  109339. NullEngine.prototype.setColor3 = function (uniform, color3) {
  109340. };
  109341. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  109342. };
  109343. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  109344. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  109345. if (this._alphaMode === mode) {
  109346. return;
  109347. }
  109348. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  109349. if (!noDepthWriteChange) {
  109350. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  109351. }
  109352. this._alphaMode = mode;
  109353. };
  109354. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  109355. };
  109356. NullEngine.prototype.wipeCaches = function (bruteForce) {
  109357. if (this.preventCacheWipeBetweenFrames) {
  109358. return;
  109359. }
  109360. this.resetTextureCache();
  109361. this._currentEffect = null;
  109362. if (bruteForce) {
  109363. this._currentProgram = null;
  109364. this._stencilState.reset();
  109365. this._depthCullingState.reset();
  109366. this._alphaState.reset();
  109367. }
  109368. this._cachedVertexBuffers = null;
  109369. this._cachedIndexBuffer = null;
  109370. this._cachedEffectForVertexBuffers = null;
  109371. };
  109372. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  109373. };
  109374. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  109375. };
  109376. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  109377. };
  109378. /** @hidden */
  109379. NullEngine.prototype._createTexture = function () {
  109380. return {};
  109381. };
  109382. /** @hidden */
  109383. NullEngine.prototype._releaseTexture = function (texture) {
  109384. };
  109385. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  109386. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109387. if (onLoad === void 0) { onLoad = null; }
  109388. if (onError === void 0) { onError = null; }
  109389. if (buffer === void 0) { buffer = null; }
  109390. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  109391. var url = String(urlArg);
  109392. texture.url = url;
  109393. texture.generateMipMaps = !noMipmap;
  109394. texture.samplingMode = samplingMode;
  109395. texture.invertY = invertY;
  109396. texture.baseWidth = this._options.textureSize;
  109397. texture.baseHeight = this._options.textureSize;
  109398. texture.width = this._options.textureSize;
  109399. texture.height = this._options.textureSize;
  109400. if (format) {
  109401. texture.format = format;
  109402. }
  109403. texture.isReady = true;
  109404. if (onLoad) {
  109405. onLoad();
  109406. }
  109407. this._internalTexturesCache.push(texture);
  109408. return texture;
  109409. };
  109410. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  109411. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  109412. if (options !== undefined && typeof options === "object") {
  109413. fullOptions.generateMipMaps = options.generateMipMaps;
  109414. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  109415. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  109416. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  109417. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  109418. }
  109419. else {
  109420. fullOptions.generateMipMaps = options;
  109421. fullOptions.generateDepthBuffer = true;
  109422. fullOptions.generateStencilBuffer = false;
  109423. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109424. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  109425. }
  109426. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  109427. var width = size.width || size;
  109428. var height = size.height || size;
  109429. texture._depthStencilBuffer = {};
  109430. texture._framebuffer = {};
  109431. texture.baseWidth = width;
  109432. texture.baseHeight = height;
  109433. texture.width = width;
  109434. texture.height = height;
  109435. texture.isReady = true;
  109436. texture.samples = 1;
  109437. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  109438. texture.samplingMode = fullOptions.samplingMode;
  109439. texture.type = fullOptions.type;
  109440. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  109441. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  109442. this._internalTexturesCache.push(texture);
  109443. return texture;
  109444. };
  109445. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  109446. texture.samplingMode = samplingMode;
  109447. };
  109448. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  109449. if (this._currentRenderTarget) {
  109450. this.unBindFramebuffer(this._currentRenderTarget);
  109451. }
  109452. this._currentRenderTarget = texture;
  109453. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  109454. if (this._cachedViewport && !forceFullscreenViewport) {
  109455. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  109456. }
  109457. };
  109458. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  109459. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  109460. this._currentRenderTarget = null;
  109461. if (onBeforeUnbind) {
  109462. if (texture._MSAAFramebuffer) {
  109463. this._currentFramebuffer = texture._framebuffer;
  109464. }
  109465. onBeforeUnbind();
  109466. }
  109467. this._currentFramebuffer = null;
  109468. };
  109469. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  109470. var vbo = {
  109471. capacity: 1,
  109472. references: 1,
  109473. is32Bits: false
  109474. };
  109475. return vbo;
  109476. };
  109477. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  109478. if (premulAlpha === void 0) { premulAlpha = false; }
  109479. };
  109480. /**
  109481. * @hidden
  109482. * Get the current error code of the webGL context
  109483. * @returns the error code
  109484. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  109485. */
  109486. NullEngine.prototype.getError = function () {
  109487. return 0;
  109488. };
  109489. /** @hidden */
  109490. NullEngine.prototype._getUnpackAlignement = function () {
  109491. return 1;
  109492. };
  109493. /** @hidden */
  109494. NullEngine.prototype._unpackFlipY = function (value) {
  109495. };
  109496. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  109497. if (offset === void 0) { offset = 0; }
  109498. };
  109499. /**
  109500. * Updates a dynamic vertex buffer.
  109501. * @param vertexBuffer the vertex buffer to update
  109502. * @param data the data used to update the vertex buffer
  109503. * @param byteOffset the byte offset of the data (optional)
  109504. * @param byteLength the byte length of the data (optional)
  109505. */
  109506. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  109507. };
  109508. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  109509. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  109510. this._boundTexturesCache[this._activeChannel] = texture;
  109511. return true;
  109512. }
  109513. return false;
  109514. };
  109515. /** @hidden */
  109516. NullEngine.prototype._bindTexture = function (channel, texture) {
  109517. if (channel < 0) {
  109518. return;
  109519. }
  109520. this._bindTextureDirectly(0, texture);
  109521. };
  109522. /** @hidden */
  109523. NullEngine.prototype._releaseBuffer = function (buffer) {
  109524. buffer.references--;
  109525. if (buffer.references === 0) {
  109526. return true;
  109527. }
  109528. return false;
  109529. };
  109530. NullEngine.prototype.releaseEffects = function () {
  109531. };
  109532. NullEngine.prototype.displayLoadingUI = function () {
  109533. };
  109534. NullEngine.prototype.hideLoadingUI = function () {
  109535. };
  109536. /** @hidden */
  109537. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  109538. if (faceIndex === void 0) { faceIndex = 0; }
  109539. if (lod === void 0) { lod = 0; }
  109540. };
  109541. /** @hidden */
  109542. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  109543. if (faceIndex === void 0) { faceIndex = 0; }
  109544. if (lod === void 0) { lod = 0; }
  109545. };
  109546. /** @hidden */
  109547. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  109548. if (faceIndex === void 0) { faceIndex = 0; }
  109549. if (lod === void 0) { lod = 0; }
  109550. };
  109551. /** @hidden */
  109552. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  109553. if (faceIndex === void 0) { faceIndex = 0; }
  109554. if (lod === void 0) { lod = 0; }
  109555. };
  109556. return NullEngine;
  109557. }(BABYLON.Engine));
  109558. BABYLON.NullEngine = NullEngine;
  109559. })(BABYLON || (BABYLON = {}));
  109560. //# sourceMappingURL=babylon.nullEngine.js.map
  109561. var BABYLON;
  109562. (function (BABYLON) {
  109563. /**
  109564. * This class can be used to get instrumentation data from a Babylon engine
  109565. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109566. */
  109567. var EngineInstrumentation = /** @class */ (function () {
  109568. /**
  109569. * Instantiates a new engine instrumentation.
  109570. * This class can be used to get instrumentation data from a Babylon engine
  109571. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  109572. * @param engine Defines the engine to instrument
  109573. */
  109574. function EngineInstrumentation(
  109575. /**
  109576. * Define the instrumented engine.
  109577. */
  109578. engine) {
  109579. this.engine = engine;
  109580. this._captureGPUFrameTime = false;
  109581. this._gpuFrameTime = new BABYLON.PerfCounter();
  109582. this._captureShaderCompilationTime = false;
  109583. this._shaderCompilationTime = new BABYLON.PerfCounter();
  109584. // Observers
  109585. this._onBeginFrameObserver = null;
  109586. this._onEndFrameObserver = null;
  109587. this._onBeforeShaderCompilationObserver = null;
  109588. this._onAfterShaderCompilationObserver = null;
  109589. }
  109590. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  109591. // Properties
  109592. /**
  109593. * Gets the perf counter used for GPU frame time
  109594. */
  109595. get: function () {
  109596. return this._gpuFrameTime;
  109597. },
  109598. enumerable: true,
  109599. configurable: true
  109600. });
  109601. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  109602. /**
  109603. * Gets the GPU frame time capture status
  109604. */
  109605. get: function () {
  109606. return this._captureGPUFrameTime;
  109607. },
  109608. /**
  109609. * Enable or disable the GPU frame time capture
  109610. */
  109611. set: function (value) {
  109612. var _this = this;
  109613. if (value === this._captureGPUFrameTime) {
  109614. return;
  109615. }
  109616. this._captureGPUFrameTime = value;
  109617. if (value) {
  109618. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  109619. if (!_this._gpuFrameTimeToken) {
  109620. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  109621. }
  109622. });
  109623. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  109624. if (!_this._gpuFrameTimeToken) {
  109625. return;
  109626. }
  109627. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  109628. if (time > -1) {
  109629. _this._gpuFrameTimeToken = null;
  109630. _this._gpuFrameTime.fetchNewFrame();
  109631. _this._gpuFrameTime.addCount(time, true);
  109632. }
  109633. });
  109634. }
  109635. else {
  109636. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109637. this._onBeginFrameObserver = null;
  109638. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109639. this._onEndFrameObserver = null;
  109640. }
  109641. },
  109642. enumerable: true,
  109643. configurable: true
  109644. });
  109645. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  109646. /**
  109647. * Gets the perf counter used for shader compilation time
  109648. */
  109649. get: function () {
  109650. return this._shaderCompilationTime;
  109651. },
  109652. enumerable: true,
  109653. configurable: true
  109654. });
  109655. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  109656. /**
  109657. * Gets the shader compilation time capture status
  109658. */
  109659. get: function () {
  109660. return this._captureShaderCompilationTime;
  109661. },
  109662. /**
  109663. * Enable or disable the shader compilation time capture
  109664. */
  109665. set: function (value) {
  109666. var _this = this;
  109667. if (value === this._captureShaderCompilationTime) {
  109668. return;
  109669. }
  109670. this._captureShaderCompilationTime = value;
  109671. if (value) {
  109672. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  109673. _this._shaderCompilationTime.fetchNewFrame();
  109674. _this._shaderCompilationTime.beginMonitoring();
  109675. });
  109676. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  109677. _this._shaderCompilationTime.endMonitoring();
  109678. });
  109679. }
  109680. else {
  109681. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109682. this._onBeforeShaderCompilationObserver = null;
  109683. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109684. this._onAfterShaderCompilationObserver = null;
  109685. }
  109686. },
  109687. enumerable: true,
  109688. configurable: true
  109689. });
  109690. /**
  109691. * Dispose and release associated resources.
  109692. */
  109693. EngineInstrumentation.prototype.dispose = function () {
  109694. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  109695. this._onBeginFrameObserver = null;
  109696. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  109697. this._onEndFrameObserver = null;
  109698. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  109699. this._onBeforeShaderCompilationObserver = null;
  109700. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  109701. this._onAfterShaderCompilationObserver = null;
  109702. this.engine = null;
  109703. };
  109704. return EngineInstrumentation;
  109705. }());
  109706. BABYLON.EngineInstrumentation = EngineInstrumentation;
  109707. })(BABYLON || (BABYLON = {}));
  109708. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  109709. var BABYLON;
  109710. (function (BABYLON) {
  109711. /**
  109712. * This class can be used to get instrumentation data from a Babylon engine
  109713. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109714. */
  109715. var SceneInstrumentation = /** @class */ (function () {
  109716. /**
  109717. * Instantiates a new scene instrumentation.
  109718. * This class can be used to get instrumentation data from a Babylon engine
  109719. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  109720. * @param scene Defines the scene to instrument
  109721. */
  109722. function SceneInstrumentation(
  109723. /**
  109724. * Defines the scene to instrument
  109725. */
  109726. scene) {
  109727. var _this = this;
  109728. this.scene = scene;
  109729. this._captureActiveMeshesEvaluationTime = false;
  109730. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  109731. this._captureRenderTargetsRenderTime = false;
  109732. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  109733. this._captureFrameTime = false;
  109734. this._frameTime = new BABYLON.PerfCounter();
  109735. this._captureRenderTime = false;
  109736. this._renderTime = new BABYLON.PerfCounter();
  109737. this._captureInterFrameTime = false;
  109738. this._interFrameTime = new BABYLON.PerfCounter();
  109739. this._captureParticlesRenderTime = false;
  109740. this._particlesRenderTime = new BABYLON.PerfCounter();
  109741. this._captureSpritesRenderTime = false;
  109742. this._spritesRenderTime = new BABYLON.PerfCounter();
  109743. this._capturePhysicsTime = false;
  109744. this._physicsTime = new BABYLON.PerfCounter();
  109745. this._captureAnimationsTime = false;
  109746. this._animationsTime = new BABYLON.PerfCounter();
  109747. this._captureCameraRenderTime = false;
  109748. this._cameraRenderTime = new BABYLON.PerfCounter();
  109749. // Observers
  109750. this._onBeforeActiveMeshesEvaluationObserver = null;
  109751. this._onAfterActiveMeshesEvaluationObserver = null;
  109752. this._onBeforeRenderTargetsRenderObserver = null;
  109753. this._onAfterRenderTargetsRenderObserver = null;
  109754. this._onAfterRenderObserver = null;
  109755. this._onBeforeDrawPhaseObserver = null;
  109756. this._onAfterDrawPhaseObserver = null;
  109757. this._onBeforeAnimationsObserver = null;
  109758. this._onBeforeParticlesRenderingObserver = null;
  109759. this._onAfterParticlesRenderingObserver = null;
  109760. this._onBeforeSpritesRenderingObserver = null;
  109761. this._onAfterSpritesRenderingObserver = null;
  109762. this._onBeforePhysicsObserver = null;
  109763. this._onAfterPhysicsObserver = null;
  109764. this._onAfterAnimationsObserver = null;
  109765. this._onBeforeCameraRenderObserver = null;
  109766. this._onAfterCameraRenderObserver = null;
  109767. // Before render
  109768. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  109769. if (_this._captureActiveMeshesEvaluationTime) {
  109770. _this._activeMeshesEvaluationTime.fetchNewFrame();
  109771. }
  109772. if (_this._captureRenderTargetsRenderTime) {
  109773. _this._renderTargetsRenderTime.fetchNewFrame();
  109774. }
  109775. if (_this._captureFrameTime) {
  109776. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  109777. _this._frameTime.beginMonitoring();
  109778. }
  109779. if (_this._captureInterFrameTime) {
  109780. _this._interFrameTime.endMonitoring();
  109781. }
  109782. if (_this._captureParticlesRenderTime) {
  109783. _this._particlesRenderTime.fetchNewFrame();
  109784. }
  109785. if (_this._captureSpritesRenderTime) {
  109786. _this._spritesRenderTime.fetchNewFrame();
  109787. }
  109788. if (_this._captureAnimationsTime) {
  109789. _this._animationsTime.beginMonitoring();
  109790. }
  109791. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  109792. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  109793. });
  109794. // After render
  109795. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  109796. if (_this._captureFrameTime) {
  109797. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  109798. _this._frameTime.endMonitoring();
  109799. }
  109800. if (_this._captureRenderTime) {
  109801. _this._renderTime.endMonitoring(false);
  109802. }
  109803. if (_this._captureInterFrameTime) {
  109804. _this._interFrameTime.beginMonitoring();
  109805. }
  109806. });
  109807. }
  109808. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  109809. // Properties
  109810. /**
  109811. * Gets the perf counter used for active meshes evaluation time
  109812. */
  109813. get: function () {
  109814. return this._activeMeshesEvaluationTime;
  109815. },
  109816. enumerable: true,
  109817. configurable: true
  109818. });
  109819. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  109820. /**
  109821. * Gets the active meshes evaluation time capture status
  109822. */
  109823. get: function () {
  109824. return this._captureActiveMeshesEvaluationTime;
  109825. },
  109826. /**
  109827. * Enable or disable the active meshes evaluation time capture
  109828. */
  109829. set: function (value) {
  109830. var _this = this;
  109831. if (value === this._captureActiveMeshesEvaluationTime) {
  109832. return;
  109833. }
  109834. this._captureActiveMeshesEvaluationTime = value;
  109835. if (value) {
  109836. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  109837. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  109838. _this._activeMeshesEvaluationTime.beginMonitoring();
  109839. });
  109840. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  109841. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  109842. _this._activeMeshesEvaluationTime.endMonitoring();
  109843. });
  109844. }
  109845. else {
  109846. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109847. this._onBeforeActiveMeshesEvaluationObserver = null;
  109848. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109849. this._onAfterActiveMeshesEvaluationObserver = null;
  109850. }
  109851. },
  109852. enumerable: true,
  109853. configurable: true
  109854. });
  109855. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  109856. /**
  109857. * Gets the perf counter used for render targets render time
  109858. */
  109859. get: function () {
  109860. return this._renderTargetsRenderTime;
  109861. },
  109862. enumerable: true,
  109863. configurable: true
  109864. });
  109865. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  109866. /**
  109867. * Gets the render targets render time capture status
  109868. */
  109869. get: function () {
  109870. return this._captureRenderTargetsRenderTime;
  109871. },
  109872. /**
  109873. * Enable or disable the render targets render time capture
  109874. */
  109875. set: function (value) {
  109876. var _this = this;
  109877. if (value === this._captureRenderTargetsRenderTime) {
  109878. return;
  109879. }
  109880. this._captureRenderTargetsRenderTime = value;
  109881. if (value) {
  109882. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  109883. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  109884. _this._renderTargetsRenderTime.beginMonitoring();
  109885. });
  109886. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  109887. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  109888. _this._renderTargetsRenderTime.endMonitoring(false);
  109889. });
  109890. }
  109891. else {
  109892. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109893. this._onBeforeRenderTargetsRenderObserver = null;
  109894. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109895. this._onAfterRenderTargetsRenderObserver = null;
  109896. }
  109897. },
  109898. enumerable: true,
  109899. configurable: true
  109900. });
  109901. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  109902. /**
  109903. * Gets the perf counter used for particles render time
  109904. */
  109905. get: function () {
  109906. return this._particlesRenderTime;
  109907. },
  109908. enumerable: true,
  109909. configurable: true
  109910. });
  109911. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  109912. /**
  109913. * Gets the particles render time capture status
  109914. */
  109915. get: function () {
  109916. return this._captureParticlesRenderTime;
  109917. },
  109918. /**
  109919. * Enable or disable the particles render time capture
  109920. */
  109921. set: function (value) {
  109922. var _this = this;
  109923. if (value === this._captureParticlesRenderTime) {
  109924. return;
  109925. }
  109926. this._captureParticlesRenderTime = value;
  109927. if (value) {
  109928. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  109929. BABYLON.Tools.StartPerformanceCounter("Particles");
  109930. _this._particlesRenderTime.beginMonitoring();
  109931. });
  109932. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  109933. BABYLON.Tools.EndPerformanceCounter("Particles");
  109934. _this._particlesRenderTime.endMonitoring(false);
  109935. });
  109936. }
  109937. else {
  109938. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109939. this._onBeforeParticlesRenderingObserver = null;
  109940. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109941. this._onAfterParticlesRenderingObserver = null;
  109942. }
  109943. },
  109944. enumerable: true,
  109945. configurable: true
  109946. });
  109947. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  109948. /**
  109949. * Gets the perf counter used for sprites render time
  109950. */
  109951. get: function () {
  109952. return this._spritesRenderTime;
  109953. },
  109954. enumerable: true,
  109955. configurable: true
  109956. });
  109957. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  109958. /**
  109959. * Gets the sprites render time capture status
  109960. */
  109961. get: function () {
  109962. return this._captureSpritesRenderTime;
  109963. },
  109964. /**
  109965. * Enable or disable the sprites render time capture
  109966. */
  109967. set: function (value) {
  109968. var _this = this;
  109969. if (value === this._captureSpritesRenderTime) {
  109970. return;
  109971. }
  109972. this._captureSpritesRenderTime = value;
  109973. if (!this.scene.spriteManagers) {
  109974. return;
  109975. }
  109976. if (value) {
  109977. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  109978. BABYLON.Tools.StartPerformanceCounter("Sprites");
  109979. _this._spritesRenderTime.beginMonitoring();
  109980. });
  109981. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  109982. BABYLON.Tools.EndPerformanceCounter("Sprites");
  109983. _this._spritesRenderTime.endMonitoring(false);
  109984. });
  109985. }
  109986. else {
  109987. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109988. this._onBeforeSpritesRenderingObserver = null;
  109989. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109990. this._onAfterSpritesRenderingObserver = null;
  109991. }
  109992. },
  109993. enumerable: true,
  109994. configurable: true
  109995. });
  109996. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  109997. /**
  109998. * Gets the perf counter used for physics time
  109999. */
  110000. get: function () {
  110001. return this._physicsTime;
  110002. },
  110003. enumerable: true,
  110004. configurable: true
  110005. });
  110006. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  110007. /**
  110008. * Gets the physics time capture status
  110009. */
  110010. get: function () {
  110011. return this._capturePhysicsTime;
  110012. },
  110013. /**
  110014. * Enable or disable the physics time capture
  110015. */
  110016. set: function (value) {
  110017. var _this = this;
  110018. if (value === this._capturePhysicsTime) {
  110019. return;
  110020. }
  110021. if (!this.scene.onBeforePhysicsObservable) {
  110022. return;
  110023. }
  110024. this._capturePhysicsTime = value;
  110025. if (value) {
  110026. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  110027. BABYLON.Tools.StartPerformanceCounter("Physics");
  110028. _this._physicsTime.beginMonitoring();
  110029. });
  110030. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  110031. BABYLON.Tools.EndPerformanceCounter("Physics");
  110032. _this._physicsTime.endMonitoring();
  110033. });
  110034. }
  110035. else {
  110036. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110037. this._onBeforePhysicsObserver = null;
  110038. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110039. this._onAfterPhysicsObserver = null;
  110040. }
  110041. },
  110042. enumerable: true,
  110043. configurable: true
  110044. });
  110045. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  110046. /**
  110047. * Gets the perf counter used for animations time
  110048. */
  110049. get: function () {
  110050. return this._animationsTime;
  110051. },
  110052. enumerable: true,
  110053. configurable: true
  110054. });
  110055. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  110056. /**
  110057. * Gets the animations time capture status
  110058. */
  110059. get: function () {
  110060. return this._captureAnimationsTime;
  110061. },
  110062. /**
  110063. * Enable or disable the animations time capture
  110064. */
  110065. set: function (value) {
  110066. var _this = this;
  110067. if (value === this._captureAnimationsTime) {
  110068. return;
  110069. }
  110070. this._captureAnimationsTime = value;
  110071. if (value) {
  110072. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  110073. _this._animationsTime.endMonitoring();
  110074. });
  110075. }
  110076. else {
  110077. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110078. this._onAfterAnimationsObserver = null;
  110079. }
  110080. },
  110081. enumerable: true,
  110082. configurable: true
  110083. });
  110084. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  110085. /**
  110086. * Gets the perf counter used for frame time capture
  110087. */
  110088. get: function () {
  110089. return this._frameTime;
  110090. },
  110091. enumerable: true,
  110092. configurable: true
  110093. });
  110094. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  110095. /**
  110096. * Gets the frame time capture status
  110097. */
  110098. get: function () {
  110099. return this._captureFrameTime;
  110100. },
  110101. /**
  110102. * Enable or disable the frame time capture
  110103. */
  110104. set: function (value) {
  110105. this._captureFrameTime = value;
  110106. },
  110107. enumerable: true,
  110108. configurable: true
  110109. });
  110110. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  110111. /**
  110112. * Gets the perf counter used for inter-frames time capture
  110113. */
  110114. get: function () {
  110115. return this._interFrameTime;
  110116. },
  110117. enumerable: true,
  110118. configurable: true
  110119. });
  110120. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  110121. /**
  110122. * Gets the inter-frames time capture status
  110123. */
  110124. get: function () {
  110125. return this._captureInterFrameTime;
  110126. },
  110127. /**
  110128. * Enable or disable the inter-frames time capture
  110129. */
  110130. set: function (value) {
  110131. this._captureInterFrameTime = value;
  110132. },
  110133. enumerable: true,
  110134. configurable: true
  110135. });
  110136. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  110137. /**
  110138. * Gets the perf counter used for render time capture
  110139. */
  110140. get: function () {
  110141. return this._renderTime;
  110142. },
  110143. enumerable: true,
  110144. configurable: true
  110145. });
  110146. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  110147. /**
  110148. * Gets the render time capture status
  110149. */
  110150. get: function () {
  110151. return this._captureRenderTime;
  110152. },
  110153. /**
  110154. * Enable or disable the render time capture
  110155. */
  110156. set: function (value) {
  110157. var _this = this;
  110158. if (value === this._captureRenderTime) {
  110159. return;
  110160. }
  110161. this._captureRenderTime = value;
  110162. if (value) {
  110163. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  110164. _this._renderTime.beginMonitoring();
  110165. BABYLON.Tools.StartPerformanceCounter("Main render");
  110166. });
  110167. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  110168. _this._renderTime.endMonitoring(false);
  110169. BABYLON.Tools.EndPerformanceCounter("Main render");
  110170. });
  110171. }
  110172. else {
  110173. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110174. this._onBeforeDrawPhaseObserver = null;
  110175. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110176. this._onAfterDrawPhaseObserver = null;
  110177. }
  110178. },
  110179. enumerable: true,
  110180. configurable: true
  110181. });
  110182. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  110183. /**
  110184. * Gets the perf counter used for camera render time capture
  110185. */
  110186. get: function () {
  110187. return this._cameraRenderTime;
  110188. },
  110189. enumerable: true,
  110190. configurable: true
  110191. });
  110192. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  110193. /**
  110194. * Gets the camera render time capture status
  110195. */
  110196. get: function () {
  110197. return this._captureCameraRenderTime;
  110198. },
  110199. /**
  110200. * Enable or disable the camera render time capture
  110201. */
  110202. set: function (value) {
  110203. var _this = this;
  110204. if (value === this._captureCameraRenderTime) {
  110205. return;
  110206. }
  110207. this._captureCameraRenderTime = value;
  110208. if (value) {
  110209. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  110210. _this._cameraRenderTime.beginMonitoring();
  110211. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  110212. });
  110213. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  110214. _this._cameraRenderTime.endMonitoring(false);
  110215. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  110216. });
  110217. }
  110218. else {
  110219. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110220. this._onBeforeCameraRenderObserver = null;
  110221. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110222. this._onAfterCameraRenderObserver = null;
  110223. }
  110224. },
  110225. enumerable: true,
  110226. configurable: true
  110227. });
  110228. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  110229. /**
  110230. * Gets the perf counter used for draw calls
  110231. */
  110232. get: function () {
  110233. return this.scene.getEngine()._drawCalls;
  110234. },
  110235. enumerable: true,
  110236. configurable: true
  110237. });
  110238. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  110239. /**
  110240. * Gets the perf counter used for texture collisions
  110241. */
  110242. get: function () {
  110243. return this.scene.getEngine()._textureCollisions;
  110244. },
  110245. enumerable: true,
  110246. configurable: true
  110247. });
  110248. /**
  110249. * Dispose and release associated resources.
  110250. */
  110251. SceneInstrumentation.prototype.dispose = function () {
  110252. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110253. this._onAfterRenderObserver = null;
  110254. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  110255. this._onBeforeActiveMeshesEvaluationObserver = null;
  110256. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  110257. this._onAfterActiveMeshesEvaluationObserver = null;
  110258. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  110259. this._onBeforeRenderTargetsRenderObserver = null;
  110260. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  110261. this._onAfterRenderTargetsRenderObserver = null;
  110262. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  110263. this._onBeforeAnimationsObserver = null;
  110264. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  110265. this._onBeforeParticlesRenderingObserver = null;
  110266. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  110267. this._onAfterParticlesRenderingObserver = null;
  110268. if (this._onBeforeSpritesRenderingObserver) {
  110269. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  110270. this._onBeforeSpritesRenderingObserver = null;
  110271. }
  110272. if (this._onAfterSpritesRenderingObserver) {
  110273. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  110274. this._onAfterSpritesRenderingObserver = null;
  110275. }
  110276. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  110277. this._onBeforeDrawPhaseObserver = null;
  110278. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  110279. this._onAfterDrawPhaseObserver = null;
  110280. if (this._onBeforePhysicsObserver) {
  110281. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  110282. this._onBeforePhysicsObserver = null;
  110283. }
  110284. if (this._onAfterPhysicsObserver) {
  110285. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  110286. this._onAfterPhysicsObserver = null;
  110287. }
  110288. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  110289. this._onAfterAnimationsObserver = null;
  110290. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  110291. this._onBeforeCameraRenderObserver = null;
  110292. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  110293. this._onAfterCameraRenderObserver = null;
  110294. this.scene = null;
  110295. };
  110296. return SceneInstrumentation;
  110297. }());
  110298. BABYLON.SceneInstrumentation = SceneInstrumentation;
  110299. })(BABYLON || (BABYLON = {}));
  110300. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  110301. var BABYLON;
  110302. (function (BABYLON) {
  110303. /**
  110304. * @hidden
  110305. **/
  110306. var _TimeToken = /** @class */ (function () {
  110307. function _TimeToken() {
  110308. this._timeElapsedQueryEnded = false;
  110309. }
  110310. return _TimeToken;
  110311. }());
  110312. BABYLON._TimeToken = _TimeToken;
  110313. })(BABYLON || (BABYLON = {}));
  110314. //# sourceMappingURL=babylon.timeToken.js.map
  110315. var BABYLON;
  110316. (function (BABYLON) {
  110317. /**
  110318. * Background material defines definition.
  110319. * @hidden Mainly internal Use
  110320. */
  110321. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  110322. __extends(BackgroundMaterialDefines, _super);
  110323. /**
  110324. * Constructor of the defines.
  110325. */
  110326. function BackgroundMaterialDefines() {
  110327. var _this = _super.call(this) || this;
  110328. /**
  110329. * True if the diffuse texture is in use.
  110330. */
  110331. _this.DIFFUSE = false;
  110332. /**
  110333. * The direct UV channel to use.
  110334. */
  110335. _this.DIFFUSEDIRECTUV = 0;
  110336. /**
  110337. * True if the diffuse texture is in gamma space.
  110338. */
  110339. _this.GAMMADIFFUSE = false;
  110340. /**
  110341. * True if the diffuse texture has opacity in the alpha channel.
  110342. */
  110343. _this.DIFFUSEHASALPHA = false;
  110344. /**
  110345. * True if you want the material to fade to transparent at grazing angle.
  110346. */
  110347. _this.OPACITYFRESNEL = false;
  110348. /**
  110349. * True if an extra blur needs to be added in the reflection.
  110350. */
  110351. _this.REFLECTIONBLUR = false;
  110352. /**
  110353. * True if you want the material to fade to reflection at grazing angle.
  110354. */
  110355. _this.REFLECTIONFRESNEL = false;
  110356. /**
  110357. * True if you want the material to falloff as far as you move away from the scene center.
  110358. */
  110359. _this.REFLECTIONFALLOFF = false;
  110360. /**
  110361. * False if the current Webgl implementation does not support the texture lod extension.
  110362. */
  110363. _this.TEXTURELODSUPPORT = false;
  110364. /**
  110365. * True to ensure the data are premultiplied.
  110366. */
  110367. _this.PREMULTIPLYALPHA = false;
  110368. /**
  110369. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  110370. */
  110371. _this.USERGBCOLOR = false;
  110372. /**
  110373. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  110374. * stays aligned with the desired configuration.
  110375. */
  110376. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  110377. /**
  110378. * True to add noise in order to reduce the banding effect.
  110379. */
  110380. _this.NOISE = false;
  110381. /**
  110382. * is the reflection texture in BGR color scheme?
  110383. * Mainly used to solve a bug in ios10 video tag
  110384. */
  110385. _this.REFLECTIONBGR = false;
  110386. _this.IMAGEPROCESSING = false;
  110387. _this.VIGNETTE = false;
  110388. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  110389. _this.VIGNETTEBLENDMODEOPAQUE = false;
  110390. _this.TONEMAPPING = false;
  110391. _this.TONEMAPPING_ACES = false;
  110392. _this.CONTRAST = false;
  110393. _this.COLORCURVES = false;
  110394. _this.COLORGRADING = false;
  110395. _this.COLORGRADING3D = false;
  110396. _this.SAMPLER3DGREENDEPTH = false;
  110397. _this.SAMPLER3DBGRMAP = false;
  110398. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  110399. _this.EXPOSURE = false;
  110400. // Reflection.
  110401. _this.REFLECTION = false;
  110402. _this.REFLECTIONMAP_3D = false;
  110403. _this.REFLECTIONMAP_SPHERICAL = false;
  110404. _this.REFLECTIONMAP_PLANAR = false;
  110405. _this.REFLECTIONMAP_CUBIC = false;
  110406. _this.REFLECTIONMAP_PROJECTION = false;
  110407. _this.REFLECTIONMAP_SKYBOX = false;
  110408. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110409. _this.REFLECTIONMAP_EXPLICIT = false;
  110410. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110411. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110412. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110413. _this.INVERTCUBICMAP = false;
  110414. _this.REFLECTIONMAP_OPPOSITEZ = false;
  110415. _this.LODINREFLECTIONALPHA = false;
  110416. _this.GAMMAREFLECTION = false;
  110417. _this.RGBDREFLECTION = false;
  110418. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  110419. // Default BJS.
  110420. _this.MAINUV1 = false;
  110421. _this.MAINUV2 = false;
  110422. _this.UV1 = false;
  110423. _this.UV2 = false;
  110424. _this.CLIPPLANE = false;
  110425. _this.CLIPPLANE2 = false;
  110426. _this.CLIPPLANE3 = false;
  110427. _this.CLIPPLANE4 = false;
  110428. _this.POINTSIZE = false;
  110429. _this.FOG = false;
  110430. _this.NORMAL = false;
  110431. _this.NUM_BONE_INFLUENCERS = 0;
  110432. _this.BonesPerMesh = 0;
  110433. _this.INSTANCES = false;
  110434. _this.SHADOWFLOAT = false;
  110435. _this.rebuild();
  110436. return _this;
  110437. }
  110438. return BackgroundMaterialDefines;
  110439. }(BABYLON.MaterialDefines));
  110440. /**
  110441. * Background material used to create an efficient environement around your scene.
  110442. */
  110443. var BackgroundMaterial = /** @class */ (function (_super) {
  110444. __extends(BackgroundMaterial, _super);
  110445. /**
  110446. * Instantiates a Background Material in the given scene
  110447. * @param name The friendly name of the material
  110448. * @param scene The scene to add the material to
  110449. */
  110450. function BackgroundMaterial(name, scene) {
  110451. var _this = _super.call(this, name, scene) || this;
  110452. /**
  110453. * Key light Color (multiply against the environement texture)
  110454. */
  110455. _this.primaryColor = BABYLON.Color3.White();
  110456. _this._primaryColorShadowLevel = 0;
  110457. _this._primaryColorHighlightLevel = 0;
  110458. /**
  110459. * Reflection Texture used in the material.
  110460. * Should be author in a specific way for the best result (refer to the documentation).
  110461. */
  110462. _this.reflectionTexture = null;
  110463. /**
  110464. * Reflection Texture level of blur.
  110465. *
  110466. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  110467. * texture twice.
  110468. */
  110469. _this.reflectionBlur = 0;
  110470. /**
  110471. * Diffuse Texture used in the material.
  110472. * Should be author in a specific way for the best result (refer to the documentation).
  110473. */
  110474. _this.diffuseTexture = null;
  110475. _this._shadowLights = null;
  110476. /**
  110477. * Specify the list of lights casting shadow on the material.
  110478. * All scene shadow lights will be included if null.
  110479. */
  110480. _this.shadowLights = null;
  110481. /**
  110482. * Helps adjusting the shadow to a softer level if required.
  110483. * 0 means black shadows and 1 means no shadows.
  110484. */
  110485. _this.shadowLevel = 0;
  110486. /**
  110487. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  110488. * It is usually zero but might be interesting to modify according to your setup.
  110489. */
  110490. _this.sceneCenter = BABYLON.Vector3.Zero();
  110491. /**
  110492. * This helps specifying that the material is falling off to the sky box at grazing angle.
  110493. * This helps ensuring a nice transition when the camera goes under the ground.
  110494. */
  110495. _this.opacityFresnel = true;
  110496. /**
  110497. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  110498. * This helps adding a mirror texture on the ground.
  110499. */
  110500. _this.reflectionFresnel = false;
  110501. /**
  110502. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  110503. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  110504. */
  110505. _this.reflectionFalloffDistance = 0.0;
  110506. /**
  110507. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  110508. */
  110509. _this.reflectionAmount = 1.0;
  110510. /**
  110511. * This specifies the weight of the reflection at grazing angle.
  110512. */
  110513. _this.reflectionReflectance0 = 0.05;
  110514. /**
  110515. * This specifies the weight of the reflection at a perpendicular point of view.
  110516. */
  110517. _this.reflectionReflectance90 = 0.5;
  110518. /**
  110519. * Helps to directly use the maps channels instead of their level.
  110520. */
  110521. _this.useRGBColor = true;
  110522. /**
  110523. * This helps reducing the banding effect that could occur on the background.
  110524. */
  110525. _this.enableNoise = false;
  110526. _this._fovMultiplier = 1.0;
  110527. /**
  110528. * Enable the FOV adjustment feature controlled by fovMultiplier.
  110529. */
  110530. _this.useEquirectangularFOV = false;
  110531. _this._maxSimultaneousLights = 4;
  110532. /**
  110533. * Number of Simultaneous lights allowed on the material.
  110534. */
  110535. _this.maxSimultaneousLights = 4;
  110536. /**
  110537. * Keep track of the image processing observer to allow dispose and replace.
  110538. */
  110539. _this._imageProcessingObserver = null;
  110540. /**
  110541. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  110542. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  110543. */
  110544. _this.switchToBGR = false;
  110545. // Temp values kept as cache in the material.
  110546. _this._renderTargets = new BABYLON.SmartArray(16);
  110547. _this._reflectionControls = BABYLON.Vector4.Zero();
  110548. _this._white = BABYLON.Color3.White();
  110549. _this._primaryShadowColor = BABYLON.Color3.Black();
  110550. _this._primaryHighlightColor = BABYLON.Color3.Black();
  110551. // Setup the default processing configuration to the scene.
  110552. _this._attachImageProcessingConfiguration(null);
  110553. _this.getRenderTargetTextures = function () {
  110554. _this._renderTargets.reset();
  110555. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  110556. _this._renderTargets.push(_this._diffuseTexture);
  110557. }
  110558. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  110559. _this._renderTargets.push(_this._reflectionTexture);
  110560. }
  110561. return _this._renderTargets;
  110562. };
  110563. return _this;
  110564. }
  110565. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  110566. /**
  110567. * Experimental Internal Use Only.
  110568. *
  110569. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  110570. * This acts as a helper to set the primary color to a more "human friendly" value.
  110571. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  110572. * output color as close as possible from the chosen value.
  110573. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  110574. * part of lighting setup.)
  110575. */
  110576. get: function () {
  110577. return this.__perceptualColor;
  110578. },
  110579. set: function (value) {
  110580. this.__perceptualColor = value;
  110581. this._computePrimaryColorFromPerceptualColor();
  110582. this._markAllSubMeshesAsLightsDirty();
  110583. },
  110584. enumerable: true,
  110585. configurable: true
  110586. });
  110587. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  110588. /**
  110589. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  110590. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  110591. */
  110592. get: function () {
  110593. return this._primaryColorShadowLevel;
  110594. },
  110595. set: function (value) {
  110596. this._primaryColorShadowLevel = value;
  110597. this._computePrimaryColors();
  110598. this._markAllSubMeshesAsLightsDirty();
  110599. },
  110600. enumerable: true,
  110601. configurable: true
  110602. });
  110603. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  110604. /**
  110605. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  110606. * The primary color is used at the level chosen to define what the white area would look.
  110607. */
  110608. get: function () {
  110609. return this._primaryColorHighlightLevel;
  110610. },
  110611. set: function (value) {
  110612. this._primaryColorHighlightLevel = value;
  110613. this._computePrimaryColors();
  110614. this._markAllSubMeshesAsLightsDirty();
  110615. },
  110616. enumerable: true,
  110617. configurable: true
  110618. });
  110619. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  110620. /**
  110621. * Sets the reflection reflectance fresnel values according to the default standard
  110622. * empirically know to work well :-)
  110623. */
  110624. set: function (value) {
  110625. var reflectionWeight = value;
  110626. if (reflectionWeight < 0.5) {
  110627. reflectionWeight = reflectionWeight * 2.0;
  110628. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  110629. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  110630. }
  110631. else {
  110632. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  110633. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  110634. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  110635. }
  110636. },
  110637. enumerable: true,
  110638. configurable: true
  110639. });
  110640. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  110641. /**
  110642. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  110643. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  110644. * Recommended to be keep at 1.0 except for special cases.
  110645. */
  110646. get: function () {
  110647. return this._fovMultiplier;
  110648. },
  110649. set: function (value) {
  110650. if (isNaN(value)) {
  110651. value = 1.0;
  110652. }
  110653. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  110654. },
  110655. enumerable: true,
  110656. configurable: true
  110657. });
  110658. /**
  110659. * Attaches a new image processing configuration to the PBR Material.
  110660. * @param configuration (if null the scene configuration will be use)
  110661. */
  110662. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  110663. var _this = this;
  110664. if (configuration === this._imageProcessingConfiguration) {
  110665. return;
  110666. }
  110667. // Detaches observer.
  110668. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110669. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110670. }
  110671. // Pick the scene configuration if needed.
  110672. if (!configuration) {
  110673. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  110674. }
  110675. else {
  110676. this._imageProcessingConfiguration = configuration;
  110677. }
  110678. // Attaches observer.
  110679. if (this._imageProcessingConfiguration) {
  110680. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  110681. _this._computePrimaryColorFromPerceptualColor();
  110682. _this._markAllSubMeshesAsImageProcessingDirty();
  110683. });
  110684. }
  110685. };
  110686. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  110687. /**
  110688. * Gets the image processing configuration used either in this material.
  110689. */
  110690. get: function () {
  110691. return this._imageProcessingConfiguration;
  110692. },
  110693. /**
  110694. * Sets the Default image processing configuration used either in the this material.
  110695. *
  110696. * If sets to null, the scene one is in use.
  110697. */
  110698. set: function (value) {
  110699. this._attachImageProcessingConfiguration(value);
  110700. // Ensure the effect will be rebuilt.
  110701. this._markAllSubMeshesAsTexturesDirty();
  110702. },
  110703. enumerable: true,
  110704. configurable: true
  110705. });
  110706. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  110707. /**
  110708. * Gets wether the color curves effect is enabled.
  110709. */
  110710. get: function () {
  110711. return this.imageProcessingConfiguration.colorCurvesEnabled;
  110712. },
  110713. /**
  110714. * Sets wether the color curves effect is enabled.
  110715. */
  110716. set: function (value) {
  110717. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  110718. },
  110719. enumerable: true,
  110720. configurable: true
  110721. });
  110722. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  110723. /**
  110724. * Gets wether the color grading effect is enabled.
  110725. */
  110726. get: function () {
  110727. return this.imageProcessingConfiguration.colorGradingEnabled;
  110728. },
  110729. /**
  110730. * Gets wether the color grading effect is enabled.
  110731. */
  110732. set: function (value) {
  110733. this.imageProcessingConfiguration.colorGradingEnabled = value;
  110734. },
  110735. enumerable: true,
  110736. configurable: true
  110737. });
  110738. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  110739. /**
  110740. * Gets wether tonemapping is enabled or not.
  110741. */
  110742. get: function () {
  110743. return this._imageProcessingConfiguration.toneMappingEnabled;
  110744. },
  110745. /**
  110746. * Sets wether tonemapping is enabled or not
  110747. */
  110748. set: function (value) {
  110749. this._imageProcessingConfiguration.toneMappingEnabled = value;
  110750. },
  110751. enumerable: true,
  110752. configurable: true
  110753. });
  110754. ;
  110755. ;
  110756. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  110757. /**
  110758. * The camera exposure used on this material.
  110759. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110760. * This corresponds to a photographic exposure.
  110761. */
  110762. get: function () {
  110763. return this._imageProcessingConfiguration.exposure;
  110764. },
  110765. /**
  110766. * The camera exposure used on this material.
  110767. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  110768. * This corresponds to a photographic exposure.
  110769. */
  110770. set: function (value) {
  110771. this._imageProcessingConfiguration.exposure = value;
  110772. },
  110773. enumerable: true,
  110774. configurable: true
  110775. });
  110776. ;
  110777. ;
  110778. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  110779. /**
  110780. * Gets The camera contrast used on this material.
  110781. */
  110782. get: function () {
  110783. return this._imageProcessingConfiguration.contrast;
  110784. },
  110785. /**
  110786. * Sets The camera contrast used on this material.
  110787. */
  110788. set: function (value) {
  110789. this._imageProcessingConfiguration.contrast = value;
  110790. },
  110791. enumerable: true,
  110792. configurable: true
  110793. });
  110794. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  110795. /**
  110796. * Gets the Color Grading 2D Lookup Texture.
  110797. */
  110798. get: function () {
  110799. return this._imageProcessingConfiguration.colorGradingTexture;
  110800. },
  110801. /**
  110802. * Sets the Color Grading 2D Lookup Texture.
  110803. */
  110804. set: function (value) {
  110805. this.imageProcessingConfiguration.colorGradingTexture = value;
  110806. },
  110807. enumerable: true,
  110808. configurable: true
  110809. });
  110810. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  110811. /**
  110812. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110813. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110814. * 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;
  110815. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110816. */
  110817. get: function () {
  110818. return this.imageProcessingConfiguration.colorCurves;
  110819. },
  110820. /**
  110821. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  110822. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  110823. * 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;
  110824. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  110825. */
  110826. set: function (value) {
  110827. this.imageProcessingConfiguration.colorCurves = value;
  110828. },
  110829. enumerable: true,
  110830. configurable: true
  110831. });
  110832. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  110833. /**
  110834. * Gets a boolean indicating that current material needs to register RTT
  110835. */
  110836. get: function () {
  110837. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  110838. return true;
  110839. }
  110840. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  110841. return true;
  110842. }
  110843. return false;
  110844. },
  110845. enumerable: true,
  110846. configurable: true
  110847. });
  110848. /**
  110849. * The entire material has been created in order to prevent overdraw.
  110850. * @returns false
  110851. */
  110852. BackgroundMaterial.prototype.needAlphaTesting = function () {
  110853. return true;
  110854. };
  110855. /**
  110856. * The entire material has been created in order to prevent overdraw.
  110857. * @returns true if blending is enable
  110858. */
  110859. BackgroundMaterial.prototype.needAlphaBlending = function () {
  110860. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  110861. };
  110862. /**
  110863. * Checks wether the material is ready to be rendered for a given mesh.
  110864. * @param mesh The mesh to render
  110865. * @param subMesh The submesh to check against
  110866. * @param useInstances Specify wether or not the material is used with instances
  110867. * @returns true if all the dependencies are ready (Textures, Effects...)
  110868. */
  110869. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  110870. var _this = this;
  110871. if (useInstances === void 0) { useInstances = false; }
  110872. if (subMesh.effect && this.isFrozen) {
  110873. if (this._wasPreviouslyReady) {
  110874. return true;
  110875. }
  110876. }
  110877. if (!subMesh._materialDefines) {
  110878. subMesh._materialDefines = new BackgroundMaterialDefines();
  110879. }
  110880. var scene = this.getScene();
  110881. var defines = subMesh._materialDefines;
  110882. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  110883. if (defines._renderId === scene.getRenderId()) {
  110884. return true;
  110885. }
  110886. }
  110887. var engine = scene.getEngine();
  110888. // Lights
  110889. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  110890. defines._needNormals = true;
  110891. // Textures
  110892. if (defines._areTexturesDirty) {
  110893. defines._needUVs = false;
  110894. if (scene.texturesEnabled) {
  110895. if (scene.getEngine().getCaps().textureLOD) {
  110896. defines.TEXTURELODSUPPORT = true;
  110897. }
  110898. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  110899. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  110900. return false;
  110901. }
  110902. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  110903. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  110904. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  110905. defines.OPACITYFRESNEL = this._opacityFresnel;
  110906. }
  110907. else {
  110908. defines.DIFFUSE = false;
  110909. defines.DIFFUSEHASALPHA = false;
  110910. defines.GAMMADIFFUSE = false;
  110911. defines.OPACITYFRESNEL = false;
  110912. }
  110913. var reflectionTexture = this._reflectionTexture;
  110914. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110915. if (!reflectionTexture.isReadyOrNotBlocking()) {
  110916. return false;
  110917. }
  110918. defines.REFLECTION = true;
  110919. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  110920. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  110921. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  110922. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  110923. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  110924. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  110925. defines.REFLECTIONBGR = this.switchToBGR;
  110926. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  110927. defines.INVERTCUBICMAP = true;
  110928. }
  110929. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  110930. switch (reflectionTexture.coordinatesMode) {
  110931. case BABYLON.Texture.EXPLICIT_MODE:
  110932. defines.REFLECTIONMAP_EXPLICIT = true;
  110933. break;
  110934. case BABYLON.Texture.PLANAR_MODE:
  110935. defines.REFLECTIONMAP_PLANAR = true;
  110936. break;
  110937. case BABYLON.Texture.PROJECTION_MODE:
  110938. defines.REFLECTIONMAP_PROJECTION = true;
  110939. break;
  110940. case BABYLON.Texture.SKYBOX_MODE:
  110941. defines.REFLECTIONMAP_SKYBOX = true;
  110942. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  110943. break;
  110944. case BABYLON.Texture.SPHERICAL_MODE:
  110945. defines.REFLECTIONMAP_SPHERICAL = true;
  110946. break;
  110947. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  110948. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  110949. break;
  110950. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  110951. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  110952. break;
  110953. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  110954. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  110955. break;
  110956. case BABYLON.Texture.CUBIC_MODE:
  110957. case BABYLON.Texture.INVCUBIC_MODE:
  110958. default:
  110959. defines.REFLECTIONMAP_CUBIC = true;
  110960. break;
  110961. }
  110962. if (this.reflectionFresnel) {
  110963. defines.REFLECTIONFRESNEL = true;
  110964. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  110965. this._reflectionControls.x = this.reflectionAmount;
  110966. this._reflectionControls.y = this.reflectionReflectance0;
  110967. this._reflectionControls.z = this.reflectionReflectance90;
  110968. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  110969. }
  110970. else {
  110971. defines.REFLECTIONFRESNEL = false;
  110972. defines.REFLECTIONFALLOFF = false;
  110973. }
  110974. }
  110975. else {
  110976. defines.REFLECTION = false;
  110977. defines.REFLECTIONFRESNEL = false;
  110978. defines.REFLECTIONFALLOFF = false;
  110979. defines.REFLECTIONBLUR = false;
  110980. defines.REFLECTIONMAP_3D = false;
  110981. defines.REFLECTIONMAP_SPHERICAL = false;
  110982. defines.REFLECTIONMAP_PLANAR = false;
  110983. defines.REFLECTIONMAP_CUBIC = false;
  110984. defines.REFLECTIONMAP_PROJECTION = false;
  110985. defines.REFLECTIONMAP_SKYBOX = false;
  110986. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  110987. defines.REFLECTIONMAP_EXPLICIT = false;
  110988. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  110989. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  110990. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  110991. defines.INVERTCUBICMAP = false;
  110992. defines.REFLECTIONMAP_OPPOSITEZ = false;
  110993. defines.LODINREFLECTIONALPHA = false;
  110994. defines.GAMMAREFLECTION = false;
  110995. defines.RGBDREFLECTION = false;
  110996. }
  110997. }
  110998. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  110999. defines.USERGBCOLOR = this._useRGBColor;
  111000. defines.NOISE = this._enableNoise;
  111001. }
  111002. if (defines._areLightsDirty) {
  111003. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  111004. }
  111005. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  111006. if (!this._imageProcessingConfiguration.isReady()) {
  111007. return false;
  111008. }
  111009. this._imageProcessingConfiguration.prepareDefines(defines);
  111010. }
  111011. // Misc.
  111012. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  111013. // Values that need to be evaluated on every frame
  111014. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  111015. // Attribs
  111016. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  111017. if (mesh) {
  111018. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  111019. mesh.createNormals(true);
  111020. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  111021. }
  111022. }
  111023. }
  111024. // Get correct effect
  111025. if (defines.isDirty) {
  111026. defines.markAsProcessed();
  111027. scene.resetCachedMaterial();
  111028. // Fallbacks
  111029. var fallbacks = new BABYLON.EffectFallbacks();
  111030. if (defines.FOG) {
  111031. fallbacks.addFallback(0, "FOG");
  111032. }
  111033. if (defines.POINTSIZE) {
  111034. fallbacks.addFallback(1, "POINTSIZE");
  111035. }
  111036. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  111037. if (defines.NUM_BONE_INFLUENCERS > 0) {
  111038. fallbacks.addCPUSkinningFallback(0, mesh);
  111039. }
  111040. //Attributes
  111041. var attribs = [BABYLON.VertexBuffer.PositionKind];
  111042. if (defines.NORMAL) {
  111043. attribs.push(BABYLON.VertexBuffer.NormalKind);
  111044. }
  111045. if (defines.UV1) {
  111046. attribs.push(BABYLON.VertexBuffer.UVKind);
  111047. }
  111048. if (defines.UV2) {
  111049. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  111050. }
  111051. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  111052. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  111053. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  111054. "vFogInfos", "vFogColor", "pointSize",
  111055. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  111056. "vPrimaryColor", "vPrimaryColorShadow",
  111057. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  111058. "shadowLevel", "alpha",
  111059. "vBackgroundCenter", "vReflectionControl",
  111060. "vDiffuseInfos", "diffuseMatrix",
  111061. ];
  111062. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  111063. var uniformBuffers = ["Material", "Scene"];
  111064. if (BABYLON.ImageProcessingConfiguration) {
  111065. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  111066. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  111067. }
  111068. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  111069. uniformsNames: uniforms,
  111070. uniformBuffersNames: uniformBuffers,
  111071. samplers: samplers,
  111072. defines: defines,
  111073. maxSimultaneousLights: this._maxSimultaneousLights
  111074. });
  111075. var onCompiled = function (effect) {
  111076. if (_this.onCompiled) {
  111077. _this.onCompiled(effect);
  111078. }
  111079. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  111080. };
  111081. var join = defines.toString();
  111082. subMesh.setEffect(scene.getEngine().createEffect("background", {
  111083. attributes: attribs,
  111084. uniformsNames: uniforms,
  111085. uniformBuffersNames: uniformBuffers,
  111086. samplers: samplers,
  111087. defines: join,
  111088. fallbacks: fallbacks,
  111089. onCompiled: onCompiled,
  111090. onError: this.onError,
  111091. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  111092. }, engine), defines);
  111093. this.buildUniformLayout();
  111094. }
  111095. if (!subMesh.effect || !subMesh.effect.isReady()) {
  111096. return false;
  111097. }
  111098. defines._renderId = scene.getRenderId();
  111099. this._wasPreviouslyReady = true;
  111100. return true;
  111101. };
  111102. /**
  111103. * Compute the primary color according to the chosen perceptual color.
  111104. */
  111105. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  111106. if (!this.__perceptualColor) {
  111107. return;
  111108. }
  111109. this._primaryColor.copyFrom(this.__perceptualColor);
  111110. // Revert gamma space.
  111111. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  111112. // Revert image processing configuration.
  111113. if (this._imageProcessingConfiguration) {
  111114. // Revert Exposure.
  111115. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  111116. }
  111117. this._computePrimaryColors();
  111118. };
  111119. /**
  111120. * Compute the highlights and shadow colors according to their chosen levels.
  111121. */
  111122. BackgroundMaterial.prototype._computePrimaryColors = function () {
  111123. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  111124. return;
  111125. }
  111126. // Find the highlight color based on the configuration.
  111127. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  111128. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  111129. // Find the shadow color based on the configuration.
  111130. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  111131. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  111132. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  111133. };
  111134. /**
  111135. * Build the uniform buffer used in the material.
  111136. */
  111137. BackgroundMaterial.prototype.buildUniformLayout = function () {
  111138. // Order is important !
  111139. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  111140. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  111141. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  111142. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  111143. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  111144. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  111145. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  111146. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  111147. this._uniformBuffer.addUniform("pointSize", 1);
  111148. this._uniformBuffer.addUniform("shadowLevel", 1);
  111149. this._uniformBuffer.addUniform("alpha", 1);
  111150. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  111151. this._uniformBuffer.addUniform("vReflectionControl", 4);
  111152. this._uniformBuffer.create();
  111153. };
  111154. /**
  111155. * Unbind the material.
  111156. */
  111157. BackgroundMaterial.prototype.unbind = function () {
  111158. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  111159. this._uniformBuffer.setTexture("diffuseSampler", null);
  111160. }
  111161. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  111162. this._uniformBuffer.setTexture("reflectionSampler", null);
  111163. }
  111164. _super.prototype.unbind.call(this);
  111165. };
  111166. /**
  111167. * Bind only the world matrix to the material.
  111168. * @param world The world matrix to bind.
  111169. */
  111170. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  111171. this._activeEffect.setMatrix("world", world);
  111172. };
  111173. /**
  111174. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  111175. * @param world The world matrix to bind.
  111176. * @param subMesh The submesh to bind for.
  111177. */
  111178. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  111179. var scene = this.getScene();
  111180. var defines = subMesh._materialDefines;
  111181. if (!defines) {
  111182. return;
  111183. }
  111184. var effect = subMesh.effect;
  111185. if (!effect) {
  111186. return;
  111187. }
  111188. this._activeEffect = effect;
  111189. // Matrices
  111190. this.bindOnlyWorldMatrix(world);
  111191. // Bones
  111192. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  111193. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  111194. if (mustRebind) {
  111195. this._uniformBuffer.bindToEffect(effect, "Material");
  111196. this.bindViewProjection(effect);
  111197. var reflectionTexture = this._reflectionTexture;
  111198. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  111199. // Texture uniforms
  111200. if (scene.texturesEnabled) {
  111201. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111202. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  111203. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  111204. }
  111205. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111206. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  111207. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  111208. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  111209. }
  111210. }
  111211. if (this.shadowLevel > 0) {
  111212. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  111213. }
  111214. this._uniformBuffer.updateFloat("alpha", this.alpha);
  111215. // Point size
  111216. if (this.pointsCloud) {
  111217. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  111218. }
  111219. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  111220. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  111221. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  111222. }
  111223. else {
  111224. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  111225. }
  111226. }
  111227. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  111228. // Textures
  111229. if (scene.texturesEnabled) {
  111230. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  111231. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  111232. }
  111233. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  111234. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  111235. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111236. }
  111237. else if (!defines.REFLECTIONBLUR) {
  111238. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  111239. }
  111240. else {
  111241. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  111242. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  111243. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  111244. }
  111245. if (defines.REFLECTIONFRESNEL) {
  111246. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  111247. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  111248. }
  111249. }
  111250. }
  111251. // Clip plane
  111252. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  111253. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  111254. }
  111255. if (mustRebind || !this.isFrozen) {
  111256. if (scene.lightsEnabled) {
  111257. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  111258. }
  111259. // View
  111260. this.bindView(effect);
  111261. // Fog
  111262. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  111263. // image processing
  111264. if (this._imageProcessingConfiguration) {
  111265. this._imageProcessingConfiguration.bind(this._activeEffect);
  111266. }
  111267. }
  111268. this._uniformBuffer.update();
  111269. this._afterBind(mesh, this._activeEffect);
  111270. };
  111271. /**
  111272. * Dispose the material.
  111273. * @param forceDisposeEffect Force disposal of the associated effect.
  111274. * @param forceDisposeTextures Force disposal of the associated textures.
  111275. */
  111276. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  111277. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  111278. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  111279. if (forceDisposeTextures) {
  111280. if (this.diffuseTexture) {
  111281. this.diffuseTexture.dispose();
  111282. }
  111283. if (this.reflectionTexture) {
  111284. this.reflectionTexture.dispose();
  111285. }
  111286. }
  111287. this._renderTargets.dispose();
  111288. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  111289. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  111290. }
  111291. _super.prototype.dispose.call(this, forceDisposeEffect);
  111292. };
  111293. /**
  111294. * Clones the material.
  111295. * @param name The cloned name.
  111296. * @returns The cloned material.
  111297. */
  111298. BackgroundMaterial.prototype.clone = function (name) {
  111299. var _this = this;
  111300. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  111301. };
  111302. /**
  111303. * Serializes the current material to its JSON representation.
  111304. * @returns The JSON representation.
  111305. */
  111306. BackgroundMaterial.prototype.serialize = function () {
  111307. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  111308. serializationObject.customType = "BABYLON.BackgroundMaterial";
  111309. return serializationObject;
  111310. };
  111311. /**
  111312. * Gets the class name of the material
  111313. * @returns "BackgroundMaterial"
  111314. */
  111315. BackgroundMaterial.prototype.getClassName = function () {
  111316. return "BackgroundMaterial";
  111317. };
  111318. /**
  111319. * Parse a JSON input to create back a background material.
  111320. * @param source The JSON data to parse
  111321. * @param scene The scene to create the parsed material in
  111322. * @param rootUrl The root url of the assets the material depends upon
  111323. * @returns the instantiated BackgroundMaterial.
  111324. */
  111325. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  111326. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  111327. };
  111328. /**
  111329. * Standard reflectance value at parallel view angle.
  111330. */
  111331. BackgroundMaterial.StandardReflectance0 = 0.05;
  111332. /**
  111333. * Standard reflectance value at grazing angle.
  111334. */
  111335. BackgroundMaterial.StandardReflectance90 = 0.5;
  111336. __decorate([
  111337. BABYLON.serializeAsColor3()
  111338. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  111339. __decorate([
  111340. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111341. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  111342. __decorate([
  111343. BABYLON.serializeAsColor3()
  111344. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  111345. __decorate([
  111346. BABYLON.serialize()
  111347. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  111348. __decorate([
  111349. BABYLON.serialize()
  111350. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  111351. __decorate([
  111352. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  111353. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  111354. __decorate([
  111355. BABYLON.serializeAsTexture()
  111356. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  111357. __decorate([
  111358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111359. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  111360. __decorate([
  111361. BABYLON.serialize()
  111362. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  111363. __decorate([
  111364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111365. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  111366. __decorate([
  111367. BABYLON.serializeAsTexture()
  111368. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  111369. __decorate([
  111370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111371. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  111372. __decorate([
  111373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111374. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  111375. __decorate([
  111376. BABYLON.serialize()
  111377. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  111378. __decorate([
  111379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111380. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  111381. __decorate([
  111382. BABYLON.serializeAsVector3()
  111383. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  111384. __decorate([
  111385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111386. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  111387. __decorate([
  111388. BABYLON.serialize()
  111389. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  111390. __decorate([
  111391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111392. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  111393. __decorate([
  111394. BABYLON.serialize()
  111395. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  111396. __decorate([
  111397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111398. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  111399. __decorate([
  111400. BABYLON.serialize()
  111401. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  111402. __decorate([
  111403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111404. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  111405. __decorate([
  111406. BABYLON.serialize()
  111407. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  111408. __decorate([
  111409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111410. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  111411. __decorate([
  111412. BABYLON.serialize()
  111413. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  111414. __decorate([
  111415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111416. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  111417. __decorate([
  111418. BABYLON.serialize()
  111419. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  111420. __decorate([
  111421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111422. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  111423. __decorate([
  111424. BABYLON.serialize()
  111425. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  111426. __decorate([
  111427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111428. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  111429. __decorate([
  111430. BABYLON.serialize()
  111431. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  111432. __decorate([
  111433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111434. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  111435. __decorate([
  111436. BABYLON.serialize()
  111437. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  111438. __decorate([
  111439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  111440. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  111441. __decorate([
  111442. BABYLON.serializeAsImageProcessingConfiguration()
  111443. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  111444. return BackgroundMaterial;
  111445. }(BABYLON.PushMaterial));
  111446. BABYLON.BackgroundMaterial = BackgroundMaterial;
  111447. })(BABYLON || (BABYLON = {}));
  111448. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  111449. var __assign = (this && this.__assign) || function () {
  111450. __assign = Object.assign || function(t) {
  111451. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111452. s = arguments[i];
  111453. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111454. t[p] = s[p];
  111455. }
  111456. return t;
  111457. };
  111458. return __assign.apply(this, arguments);
  111459. };
  111460. var BABYLON;
  111461. (function (BABYLON) {
  111462. /**
  111463. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  111464. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  111465. * It also helps with the default setup of your imageProcessing configuration.
  111466. */
  111467. var EnvironmentHelper = /** @class */ (function () {
  111468. /**
  111469. * constructor
  111470. * @param options
  111471. * @param scene The scene to add the material to
  111472. */
  111473. function EnvironmentHelper(options, scene) {
  111474. var _this = this;
  111475. this._errorHandler = function (message, exception) {
  111476. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  111477. };
  111478. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  111479. this._scene = scene;
  111480. this.onErrorObservable = new BABYLON.Observable();
  111481. this._setupBackground();
  111482. this._setupImageProcessing();
  111483. }
  111484. /**
  111485. * Creates the default options for the helper.
  111486. */
  111487. EnvironmentHelper._getDefaultOptions = function () {
  111488. return {
  111489. createGround: true,
  111490. groundSize: 15,
  111491. groundTexture: this._groundTextureCDNUrl,
  111492. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111493. groundOpacity: 0.9,
  111494. enableGroundShadow: true,
  111495. groundShadowLevel: 0.5,
  111496. enableGroundMirror: false,
  111497. groundMirrorSizeRatio: 0.3,
  111498. groundMirrorBlurKernel: 64,
  111499. groundMirrorAmount: 1,
  111500. groundMirrorFresnelWeight: 1,
  111501. groundMirrorFallOffDistance: 0,
  111502. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  111503. groundYBias: 0.00001,
  111504. createSkybox: true,
  111505. skyboxSize: 20,
  111506. skyboxTexture: this._skyboxTextureCDNUrl,
  111507. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  111508. backgroundYRotation: 0,
  111509. sizeAuto: true,
  111510. rootPosition: BABYLON.Vector3.Zero(),
  111511. setupImageProcessing: true,
  111512. environmentTexture: this._environmentTextureCDNUrl,
  111513. cameraExposure: 0.8,
  111514. cameraContrast: 1.2,
  111515. toneMappingEnabled: true,
  111516. };
  111517. };
  111518. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  111519. /**
  111520. * Gets the root mesh created by the helper.
  111521. */
  111522. get: function () {
  111523. return this._rootMesh;
  111524. },
  111525. enumerable: true,
  111526. configurable: true
  111527. });
  111528. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  111529. /**
  111530. * Gets the skybox created by the helper.
  111531. */
  111532. get: function () {
  111533. return this._skybox;
  111534. },
  111535. enumerable: true,
  111536. configurable: true
  111537. });
  111538. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  111539. /**
  111540. * Gets the skybox texture created by the helper.
  111541. */
  111542. get: function () {
  111543. return this._skyboxTexture;
  111544. },
  111545. enumerable: true,
  111546. configurable: true
  111547. });
  111548. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  111549. /**
  111550. * Gets the skybox material created by the helper.
  111551. */
  111552. get: function () {
  111553. return this._skyboxMaterial;
  111554. },
  111555. enumerable: true,
  111556. configurable: true
  111557. });
  111558. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  111559. /**
  111560. * Gets the ground mesh created by the helper.
  111561. */
  111562. get: function () {
  111563. return this._ground;
  111564. },
  111565. enumerable: true,
  111566. configurable: true
  111567. });
  111568. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  111569. /**
  111570. * Gets the ground texture created by the helper.
  111571. */
  111572. get: function () {
  111573. return this._groundTexture;
  111574. },
  111575. enumerable: true,
  111576. configurable: true
  111577. });
  111578. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  111579. /**
  111580. * Gets the ground mirror created by the helper.
  111581. */
  111582. get: function () {
  111583. return this._groundMirror;
  111584. },
  111585. enumerable: true,
  111586. configurable: true
  111587. });
  111588. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  111589. /**
  111590. * Gets the ground mirror render list to helps pushing the meshes
  111591. * you wish in the ground reflection.
  111592. */
  111593. get: function () {
  111594. if (this._groundMirror) {
  111595. return this._groundMirror.renderList;
  111596. }
  111597. return null;
  111598. },
  111599. enumerable: true,
  111600. configurable: true
  111601. });
  111602. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  111603. /**
  111604. * Gets the ground material created by the helper.
  111605. */
  111606. get: function () {
  111607. return this._groundMaterial;
  111608. },
  111609. enumerable: true,
  111610. configurable: true
  111611. });
  111612. /**
  111613. * Updates the background according to the new options
  111614. * @param options
  111615. */
  111616. EnvironmentHelper.prototype.updateOptions = function (options) {
  111617. var newOptions = __assign({}, this._options, options);
  111618. if (this._ground && !newOptions.createGround) {
  111619. this._ground.dispose();
  111620. this._ground = null;
  111621. }
  111622. if (this._groundMaterial && !newOptions.createGround) {
  111623. this._groundMaterial.dispose();
  111624. this._groundMaterial = null;
  111625. }
  111626. if (this._groundTexture) {
  111627. if (this._options.groundTexture != newOptions.groundTexture) {
  111628. this._groundTexture.dispose();
  111629. this._groundTexture = null;
  111630. }
  111631. }
  111632. if (this._skybox && !newOptions.createSkybox) {
  111633. this._skybox.dispose();
  111634. this._skybox = null;
  111635. }
  111636. if (this._skyboxMaterial && !newOptions.createSkybox) {
  111637. this._skyboxMaterial.dispose();
  111638. this._skyboxMaterial = null;
  111639. }
  111640. if (this._skyboxTexture) {
  111641. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  111642. this._skyboxTexture.dispose();
  111643. this._skyboxTexture = null;
  111644. }
  111645. }
  111646. if (this._groundMirror && !newOptions.enableGroundMirror) {
  111647. this._groundMirror.dispose();
  111648. this._groundMirror = null;
  111649. }
  111650. if (this._scene.environmentTexture) {
  111651. if (this._options.environmentTexture != newOptions.environmentTexture) {
  111652. this._scene.environmentTexture.dispose();
  111653. }
  111654. }
  111655. this._options = newOptions;
  111656. this._setupBackground();
  111657. this._setupImageProcessing();
  111658. };
  111659. /**
  111660. * Sets the primary color of all the available elements.
  111661. * @param color the main color to affect to the ground and the background
  111662. */
  111663. EnvironmentHelper.prototype.setMainColor = function (color) {
  111664. if (this.groundMaterial) {
  111665. this.groundMaterial.primaryColor = color;
  111666. }
  111667. if (this.skyboxMaterial) {
  111668. this.skyboxMaterial.primaryColor = color;
  111669. }
  111670. if (this.groundMirror) {
  111671. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  111672. }
  111673. };
  111674. /**
  111675. * Setup the image processing according to the specified options.
  111676. */
  111677. EnvironmentHelper.prototype._setupImageProcessing = function () {
  111678. if (this._options.setupImageProcessing) {
  111679. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  111680. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  111681. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  111682. this._setupEnvironmentTexture();
  111683. }
  111684. };
  111685. /**
  111686. * Setup the environment texture according to the specified options.
  111687. */
  111688. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  111689. if (this._scene.environmentTexture) {
  111690. return;
  111691. }
  111692. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  111693. this._scene.environmentTexture = this._options.environmentTexture;
  111694. return;
  111695. }
  111696. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  111697. this._scene.environmentTexture = environmentTexture;
  111698. };
  111699. /**
  111700. * Setup the background according to the specified options.
  111701. */
  111702. EnvironmentHelper.prototype._setupBackground = function () {
  111703. if (!this._rootMesh) {
  111704. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  111705. }
  111706. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  111707. var sceneSize = this._getSceneSize();
  111708. if (this._options.createGround) {
  111709. this._setupGround(sceneSize);
  111710. this._setupGroundMaterial();
  111711. this._setupGroundDiffuseTexture();
  111712. if (this._options.enableGroundMirror) {
  111713. this._setupGroundMirrorTexture(sceneSize);
  111714. }
  111715. this._setupMirrorInGroundMaterial();
  111716. }
  111717. if (this._options.createSkybox) {
  111718. this._setupSkybox(sceneSize);
  111719. this._setupSkyboxMaterial();
  111720. this._setupSkyboxReflectionTexture();
  111721. }
  111722. this._rootMesh.position.x = sceneSize.rootPosition.x;
  111723. this._rootMesh.position.z = sceneSize.rootPosition.z;
  111724. this._rootMesh.position.y = sceneSize.rootPosition.y;
  111725. };
  111726. /**
  111727. * Get the scene sizes according to the setup.
  111728. */
  111729. EnvironmentHelper.prototype._getSceneSize = function () {
  111730. var _this = this;
  111731. var groundSize = this._options.groundSize;
  111732. var skyboxSize = this._options.skyboxSize;
  111733. var rootPosition = this._options.rootPosition;
  111734. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  111735. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111736. }
  111737. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  111738. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  111739. });
  111740. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  111741. if (this._options.sizeAuto) {
  111742. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  111743. this._scene.activeCamera.upperRadiusLimit) {
  111744. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  111745. skyboxSize = groundSize;
  111746. }
  111747. var sceneDiagonalLenght = sceneDiagonal.length();
  111748. if (sceneDiagonalLenght > groundSize) {
  111749. groundSize = sceneDiagonalLenght * 2;
  111750. skyboxSize = groundSize;
  111751. }
  111752. // 10 % bigger.
  111753. groundSize *= 1.1;
  111754. skyboxSize *= 1.5;
  111755. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  111756. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  111757. }
  111758. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  111759. };
  111760. /**
  111761. * Setup the ground according to the specified options.
  111762. */
  111763. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  111764. var _this = this;
  111765. if (!this._ground || this._ground.isDisposed()) {
  111766. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  111767. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  111768. this._ground.parent = this._rootMesh;
  111769. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  111770. }
  111771. this._ground.receiveShadows = this._options.enableGroundShadow;
  111772. };
  111773. /**
  111774. * Setup the ground material according to the specified options.
  111775. */
  111776. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  111777. if (!this._groundMaterial) {
  111778. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  111779. }
  111780. this._groundMaterial.alpha = this._options.groundOpacity;
  111781. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111782. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  111783. this._groundMaterial.primaryColor = this._options.groundColor;
  111784. this._groundMaterial.useRGBColor = false;
  111785. this._groundMaterial.enableNoise = true;
  111786. if (this._ground) {
  111787. this._ground.material = this._groundMaterial;
  111788. }
  111789. };
  111790. /**
  111791. * Setup the ground diffuse texture according to the specified options.
  111792. */
  111793. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  111794. if (!this._groundMaterial) {
  111795. return;
  111796. }
  111797. if (this._groundTexture) {
  111798. return;
  111799. }
  111800. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  111801. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  111802. return;
  111803. }
  111804. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111805. diffuseTexture.gammaSpace = false;
  111806. diffuseTexture.hasAlpha = true;
  111807. this._groundMaterial.diffuseTexture = diffuseTexture;
  111808. };
  111809. /**
  111810. * Setup the ground mirror texture according to the specified options.
  111811. */
  111812. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  111813. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111814. if (!this._groundMirror) {
  111815. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  111816. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  111817. this._groundMirror.anisotropicFilteringLevel = 1;
  111818. this._groundMirror.wrapU = wrapping;
  111819. this._groundMirror.wrapV = wrapping;
  111820. this._groundMirror.gammaSpace = false;
  111821. if (this._groundMirror.renderList) {
  111822. for (var i = 0; i < this._scene.meshes.length; i++) {
  111823. var mesh = this._scene.meshes[i];
  111824. if (mesh !== this._ground &&
  111825. mesh !== this._skybox &&
  111826. mesh !== this._rootMesh) {
  111827. this._groundMirror.renderList.push(mesh);
  111828. }
  111829. }
  111830. }
  111831. }
  111832. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  111833. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  111834. };
  111835. /**
  111836. * Setup the ground to receive the mirror texture.
  111837. */
  111838. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  111839. if (this._groundMaterial) {
  111840. this._groundMaterial.reflectionTexture = this._groundMirror;
  111841. this._groundMaterial.reflectionFresnel = true;
  111842. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  111843. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  111844. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  111845. }
  111846. };
  111847. /**
  111848. * Setup the skybox according to the specified options.
  111849. */
  111850. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  111851. var _this = this;
  111852. if (!this._skybox || this._skybox.isDisposed()) {
  111853. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  111854. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  111855. }
  111856. this._skybox.parent = this._rootMesh;
  111857. };
  111858. /**
  111859. * Setup the skybox material according to the specified options.
  111860. */
  111861. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  111862. if (!this._skybox) {
  111863. return;
  111864. }
  111865. if (!this._skyboxMaterial) {
  111866. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  111867. }
  111868. this._skyboxMaterial.useRGBColor = false;
  111869. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  111870. this._skyboxMaterial.enableNoise = true;
  111871. this._skybox.material = this._skyboxMaterial;
  111872. };
  111873. /**
  111874. * Setup the skybox reflection texture according to the specified options.
  111875. */
  111876. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  111877. if (!this._skyboxMaterial) {
  111878. return;
  111879. }
  111880. if (this._skyboxTexture) {
  111881. return;
  111882. }
  111883. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  111884. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  111885. return;
  111886. }
  111887. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  111888. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111889. this._skyboxTexture.gammaSpace = false;
  111890. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  111891. };
  111892. /**
  111893. * Dispose all the elements created by the Helper.
  111894. */
  111895. EnvironmentHelper.prototype.dispose = function () {
  111896. if (this._groundMaterial) {
  111897. this._groundMaterial.dispose(true, true);
  111898. }
  111899. if (this._skyboxMaterial) {
  111900. this._skyboxMaterial.dispose(true, true);
  111901. }
  111902. this._rootMesh.dispose(false);
  111903. };
  111904. /**
  111905. * Default ground texture URL.
  111906. */
  111907. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  111908. /**
  111909. * Default skybox texture URL.
  111910. */
  111911. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  111912. /**
  111913. * Default environment texture URL.
  111914. */
  111915. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  111916. return EnvironmentHelper;
  111917. }());
  111918. BABYLON.EnvironmentHelper = EnvironmentHelper;
  111919. })(BABYLON || (BABYLON = {}));
  111920. //# sourceMappingURL=babylon.environmentHelper.js.map
  111921. var BABYLON;
  111922. (function (BABYLON) {
  111923. /** Internal class used to store shapes for emitters */
  111924. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  111925. function ParticleSystemSetEmitterCreationOptions() {
  111926. }
  111927. return ParticleSystemSetEmitterCreationOptions;
  111928. }());
  111929. /**
  111930. * Represents a set of particle systems working together to create a specific effect
  111931. */
  111932. var ParticleSystemSet = /** @class */ (function () {
  111933. function ParticleSystemSet() {
  111934. /**
  111935. * Gets the particle system list
  111936. */
  111937. this.systems = new Array();
  111938. }
  111939. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  111940. /**
  111941. * Gets the emitter node used with this set
  111942. */
  111943. get: function () {
  111944. return this._emitterNode;
  111945. },
  111946. enumerable: true,
  111947. configurable: true
  111948. });
  111949. /**
  111950. * Creates a new emitter mesh as a sphere
  111951. * @param options defines the options used to create the sphere
  111952. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  111953. * @param scene defines the hosting scene
  111954. */
  111955. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  111956. if (this._emitterNode) {
  111957. this._emitterNode.dispose();
  111958. }
  111959. this._emitterCreationOptions = {
  111960. kind: "Sphere",
  111961. options: options,
  111962. renderingGroupId: renderingGroupId
  111963. };
  111964. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  111965. emitterMesh.renderingGroupId = renderingGroupId;
  111966. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  111967. material.emissiveColor = options.color;
  111968. emitterMesh.material = material;
  111969. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111970. var system = _a[_i];
  111971. system.emitter = emitterMesh;
  111972. }
  111973. this._emitterNode = emitterMesh;
  111974. };
  111975. /**
  111976. * Starts all particle systems of the set
  111977. * @param emitter defines an optional mesh to use as emitter for the particle systems
  111978. */
  111979. ParticleSystemSet.prototype.start = function (emitter) {
  111980. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111981. var system = _a[_i];
  111982. if (emitter) {
  111983. system.emitter = emitter;
  111984. }
  111985. system.start();
  111986. }
  111987. };
  111988. /**
  111989. * Release all associated resources
  111990. */
  111991. ParticleSystemSet.prototype.dispose = function () {
  111992. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  111993. var system = _a[_i];
  111994. system.dispose();
  111995. }
  111996. this.systems = [];
  111997. if (this._emitterNode) {
  111998. this._emitterNode.dispose();
  111999. this._emitterNode = null;
  112000. }
  112001. };
  112002. /**
  112003. * Serialize the set into a JSON compatible object
  112004. * @returns a JSON compatible representation of the set
  112005. */
  112006. ParticleSystemSet.prototype.serialize = function () {
  112007. var result = {};
  112008. result.systems = [];
  112009. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  112010. var system = _a[_i];
  112011. result.systems.push(system.serialize());
  112012. }
  112013. if (this._emitterNode) {
  112014. result.emitter = this._emitterCreationOptions;
  112015. }
  112016. return result;
  112017. };
  112018. /**
  112019. * Parse a new ParticleSystemSet from a serialized source
  112020. * @param data defines a JSON compatible representation of the set
  112021. * @param scene defines the hosting scene
  112022. * @param gpu defines if we want GPU particles or CPU particles
  112023. * @returns a new ParticleSystemSet
  112024. */
  112025. ParticleSystemSet.Parse = function (data, scene, gpu) {
  112026. if (gpu === void 0) { gpu = false; }
  112027. var result = new ParticleSystemSet();
  112028. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  112029. scene = scene || BABYLON.Engine.LastCreatedScene;
  112030. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  112031. var system = _a[_i];
  112032. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  112033. }
  112034. if (data.emitter) {
  112035. var options = data.emitter.options;
  112036. switch (data.emitter.kind) {
  112037. case "Sphere":
  112038. result.setEmitterAsSphere({
  112039. diameter: options.diameter,
  112040. segments: options.segments,
  112041. color: BABYLON.Color3.FromArray(options.color)
  112042. }, data.emitter.renderingGroupId, scene);
  112043. break;
  112044. }
  112045. }
  112046. return result;
  112047. };
  112048. return ParticleSystemSet;
  112049. }());
  112050. BABYLON.ParticleSystemSet = ParticleSystemSet;
  112051. })(BABYLON || (BABYLON = {}));
  112052. //# sourceMappingURL=babylon.particleSystemSet.js.map
  112053. var BABYLON;
  112054. (function (BABYLON) {
  112055. /**
  112056. * This class is made for on one-liner static method to help creating particle system set.
  112057. */
  112058. var ParticleHelper = /** @class */ (function () {
  112059. function ParticleHelper() {
  112060. }
  112061. /**
  112062. * Create a default particle system that you can tweak
  112063. * @param emitter defines the emitter to use
  112064. * @param capacity defines the system capacity (default is 500 particles)
  112065. * @param scene defines the hosting scene
  112066. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  112067. * @returns the new Particle system
  112068. */
  112069. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  112070. if (capacity === void 0) { capacity = 500; }
  112071. if (useGPU === void 0) { useGPU = false; }
  112072. var system;
  112073. if (useGPU) {
  112074. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  112075. }
  112076. else {
  112077. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  112078. }
  112079. system.emitter = emitter;
  112080. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  112081. system.createConeEmitter(0.1, Math.PI / 4);
  112082. // Particle color
  112083. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112084. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  112085. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  112086. // Particle Size
  112087. system.minSize = 0.1;
  112088. system.maxSize = 0.1;
  112089. // Emission speed
  112090. system.minEmitPower = 2;
  112091. system.maxEmitPower = 2;
  112092. // Update speed
  112093. system.updateSpeed = 1 / 60;
  112094. system.emitRate = 30;
  112095. return system;
  112096. };
  112097. /**
  112098. * This is the main static method (one-liner) of this helper to create different particle systems
  112099. * @param type This string represents the type to the particle system to create
  112100. * @param scene The scene where the particle system should live
  112101. * @param gpu If the system will use gpu
  112102. * @returns the ParticleSystemSet created
  112103. */
  112104. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  112105. if (gpu === void 0) { gpu = false; }
  112106. if (!scene) {
  112107. scene = BABYLON.Engine.LastCreatedScene;
  112108. ;
  112109. }
  112110. var token = {};
  112111. scene._addPendingData(token);
  112112. return new Promise(function (resolve, reject) {
  112113. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  112114. scene._removePendingData(token);
  112115. return reject("Particle system with GPU is not supported.");
  112116. }
  112117. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  112118. scene._removePendingData(token);
  112119. var newData = JSON.parse(data.toString());
  112120. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  112121. }, undefined, undefined, undefined, function (req, exception) {
  112122. scene._removePendingData(token);
  112123. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  112124. });
  112125. });
  112126. };
  112127. /**
  112128. * Static function used to export a particle system to a ParticleSystemSet variable.
  112129. * Please note that the emitter shape is not exported
  112130. * @param system defines the particle systems to export
  112131. */
  112132. ParticleHelper.ExportSet = function (systems) {
  112133. var set = new BABYLON.ParticleSystemSet();
  112134. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  112135. var system = systems_1[_i];
  112136. set.systems.push(system);
  112137. }
  112138. return set;
  112139. };
  112140. /**
  112141. * Gets or sets base Assets URL
  112142. */
  112143. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  112144. return ParticleHelper;
  112145. }());
  112146. BABYLON.ParticleHelper = ParticleHelper;
  112147. })(BABYLON || (BABYLON = {}));
  112148. //# sourceMappingURL=babylon.particleHelper.js.map
  112149. var BABYLON;
  112150. (function (BABYLON) {
  112151. /**
  112152. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  112153. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  112154. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  112155. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112156. */
  112157. var VideoDome = /** @class */ (function (_super) {
  112158. __extends(VideoDome, _super);
  112159. /**
  112160. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  112161. * @param name Element's name, child elements will append suffixes for their own names.
  112162. * @param urlsOrVideo defines the url(s) or the video element to use
  112163. * @param options An object containing optional or exposed sub element properties
  112164. */
  112165. function VideoDome(name, urlsOrVideo, options, scene) {
  112166. var _this = _super.call(this, name, scene) || this;
  112167. _this._useDirectMapping = false;
  112168. // set defaults and manage values
  112169. name = name || "videoDome";
  112170. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112171. options.clickToPlay = Boolean(options.clickToPlay);
  112172. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  112173. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  112174. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112175. if (options.useDirectMapping === undefined) {
  112176. _this._useDirectMapping = true;
  112177. }
  112178. else {
  112179. _this._useDirectMapping = options.useDirectMapping;
  112180. }
  112181. _this._setReady(false);
  112182. // create
  112183. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  112184. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112185. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  112186. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112187. texture.onLoadObservable.addOnce(function () {
  112188. _this._setReady(true);
  112189. });
  112190. // configure material
  112191. material.useEquirectangularFOV = true;
  112192. material.fovMultiplier = 1.0;
  112193. material.opacityFresnel = false;
  112194. if (_this._useDirectMapping) {
  112195. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112196. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112197. material.diffuseTexture = texture;
  112198. }
  112199. else {
  112200. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112201. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112202. material.reflectionTexture = texture;
  112203. }
  112204. // configure mesh
  112205. _this._mesh.material = material;
  112206. _this._mesh.parent = _this;
  112207. // optional configuration
  112208. if (options.clickToPlay) {
  112209. scene.onPointerUp = function () {
  112210. _this._videoTexture.video.play();
  112211. };
  112212. }
  112213. return _this;
  112214. }
  112215. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  112216. /**
  112217. * Gets the video texture being displayed on the sphere
  112218. */
  112219. get: function () {
  112220. return this._videoTexture;
  112221. },
  112222. enumerable: true,
  112223. configurable: true
  112224. });
  112225. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  112226. /**
  112227. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112228. * Also see the options.resolution property.
  112229. */
  112230. get: function () {
  112231. return this._material.fovMultiplier;
  112232. },
  112233. set: function (value) {
  112234. this._material.fovMultiplier = value;
  112235. },
  112236. enumerable: true,
  112237. configurable: true
  112238. });
  112239. /**
  112240. * Releases resources associated with this node.
  112241. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112242. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112243. */
  112244. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112245. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112246. this._videoTexture.dispose();
  112247. this._mesh.dispose();
  112248. this._material.dispose();
  112249. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112250. };
  112251. return VideoDome;
  112252. }(BABYLON.TransformNode));
  112253. BABYLON.VideoDome = VideoDome;
  112254. })(BABYLON || (BABYLON = {}));
  112255. //# sourceMappingURL=babylon.videoDome.js.map
  112256. var BABYLON;
  112257. (function (BABYLON) {
  112258. /**
  112259. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  112260. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  112261. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  112262. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  112263. */
  112264. var PhotoDome = /** @class */ (function (_super) {
  112265. __extends(PhotoDome, _super);
  112266. /**
  112267. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  112268. * @param name Element's name, child elements will append suffixes for their own names.
  112269. * @param urlsOfPhoto defines the url of the photo to display
  112270. * @param options defines an object containing optional or exposed sub element properties
  112271. * @param onError defines a callback called when an error occured while loading the texture
  112272. */
  112273. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  112274. if (onError === void 0) { onError = null; }
  112275. var _this = _super.call(this, name, scene) || this;
  112276. _this._useDirectMapping = false;
  112277. /**
  112278. * Observable raised when an error occured while loading the 360 image
  112279. */
  112280. _this.onLoadErrorObservable = new BABYLON.Observable();
  112281. // set defaults and manage values
  112282. name = name || "photoDome";
  112283. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  112284. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  112285. if (options.useDirectMapping === undefined) {
  112286. _this._useDirectMapping = true;
  112287. }
  112288. else {
  112289. _this._useDirectMapping = options.useDirectMapping;
  112290. }
  112291. _this._setReady(false);
  112292. // create
  112293. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  112294. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  112295. // configure material
  112296. material.opacityFresnel = false;
  112297. material.useEquirectangularFOV = true;
  112298. material.fovMultiplier = 1.0;
  112299. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  112300. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  112301. if (onError) {
  112302. onError(message, exception);
  112303. }
  112304. });
  112305. _this.photoTexture.onLoadObservable.addOnce(function () {
  112306. _this._setReady(true);
  112307. });
  112308. // configure mesh
  112309. _this._mesh.material = material;
  112310. _this._mesh.parent = _this;
  112311. return _this;
  112312. }
  112313. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  112314. /**
  112315. * Gets or sets the texture being displayed on the sphere
  112316. */
  112317. get: function () {
  112318. return this._photoTexture;
  112319. },
  112320. set: function (value) {
  112321. if (this._photoTexture === value) {
  112322. return;
  112323. }
  112324. this._photoTexture = value;
  112325. if (this._useDirectMapping) {
  112326. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112327. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112328. this._material.diffuseTexture = this._photoTexture;
  112329. }
  112330. else {
  112331. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  112332. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  112333. this._material.reflectionTexture = this._photoTexture;
  112334. }
  112335. },
  112336. enumerable: true,
  112337. configurable: true
  112338. });
  112339. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  112340. /**
  112341. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112342. * Also see the options.resolution property.
  112343. */
  112344. get: function () {
  112345. return this._material.fovMultiplier;
  112346. },
  112347. set: function (value) {
  112348. this._material.fovMultiplier = value;
  112349. },
  112350. enumerable: true,
  112351. configurable: true
  112352. });
  112353. /**
  112354. * Releases resources associated with this node.
  112355. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  112356. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  112357. */
  112358. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  112359. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  112360. this._photoTexture.dispose();
  112361. this._mesh.dispose();
  112362. this._material.dispose();
  112363. this.onLoadErrorObservable.clear();
  112364. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  112365. };
  112366. return PhotoDome;
  112367. }(BABYLON.TransformNode));
  112368. BABYLON.PhotoDome = PhotoDome;
  112369. })(BABYLON || (BABYLON = {}));
  112370. //# sourceMappingURL=babylon.photoDome.js.map
  112371. var BABYLON;
  112372. (function (BABYLON) {
  112373. BABYLON.Engine.prototype.createQuery = function () {
  112374. return this._gl.createQuery();
  112375. };
  112376. BABYLON.Engine.prototype.deleteQuery = function (query) {
  112377. this._gl.deleteQuery(query);
  112378. return this;
  112379. };
  112380. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  112381. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  112382. };
  112383. BABYLON.Engine.prototype.getQueryResult = function (query) {
  112384. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  112385. };
  112386. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  112387. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112388. this._gl.beginQuery(glAlgorithm, query);
  112389. return this;
  112390. };
  112391. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  112392. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  112393. this._gl.endQuery(glAlgorithm);
  112394. return this;
  112395. };
  112396. BABYLON.Engine.prototype._createTimeQuery = function () {
  112397. var timerQuery = this.getCaps().timerQuery;
  112398. if (timerQuery.createQueryEXT) {
  112399. return timerQuery.createQueryEXT();
  112400. }
  112401. return this.createQuery();
  112402. };
  112403. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  112404. var timerQuery = this.getCaps().timerQuery;
  112405. if (timerQuery.deleteQueryEXT) {
  112406. timerQuery.deleteQueryEXT(query);
  112407. return;
  112408. }
  112409. this.deleteQuery(query);
  112410. };
  112411. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  112412. var timerQuery = this.getCaps().timerQuery;
  112413. if (timerQuery.getQueryObjectEXT) {
  112414. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  112415. }
  112416. return this.getQueryResult(query);
  112417. };
  112418. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  112419. var timerQuery = this.getCaps().timerQuery;
  112420. if (timerQuery.getQueryObjectEXT) {
  112421. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  112422. }
  112423. return this.isQueryResultAvailable(query);
  112424. };
  112425. BABYLON.Engine.prototype.startTimeQuery = function () {
  112426. var caps = this.getCaps();
  112427. var timerQuery = caps.timerQuery;
  112428. if (!timerQuery) {
  112429. return null;
  112430. }
  112431. var token = new BABYLON._TimeToken();
  112432. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112433. if (caps.canUseTimestampForTimerQuery) {
  112434. token._startTimeQuery = this._createTimeQuery();
  112435. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  112436. }
  112437. else {
  112438. if (this._currentNonTimestampToken) {
  112439. return this._currentNonTimestampToken;
  112440. }
  112441. token._timeElapsedQuery = this._createTimeQuery();
  112442. if (timerQuery.beginQueryEXT) {
  112443. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112444. }
  112445. else {
  112446. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  112447. }
  112448. this._currentNonTimestampToken = token;
  112449. }
  112450. return token;
  112451. };
  112452. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  112453. var caps = this.getCaps();
  112454. var timerQuery = caps.timerQuery;
  112455. if (!timerQuery || !token) {
  112456. return -1;
  112457. }
  112458. if (caps.canUseTimestampForTimerQuery) {
  112459. if (!token._startTimeQuery) {
  112460. return -1;
  112461. }
  112462. if (!token._endTimeQuery) {
  112463. token._endTimeQuery = this._createTimeQuery();
  112464. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  112465. }
  112466. }
  112467. else if (!token._timeElapsedQueryEnded) {
  112468. if (!token._timeElapsedQuery) {
  112469. return -1;
  112470. }
  112471. if (timerQuery.endQueryEXT) {
  112472. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  112473. }
  112474. else {
  112475. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  112476. }
  112477. token._timeElapsedQueryEnded = true;
  112478. }
  112479. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  112480. var available = false;
  112481. if (token._endTimeQuery) {
  112482. available = this._getTimeQueryAvailability(token._endTimeQuery);
  112483. }
  112484. else if (token._timeElapsedQuery) {
  112485. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  112486. }
  112487. if (available && !disjoint) {
  112488. var result = 0;
  112489. if (caps.canUseTimestampForTimerQuery) {
  112490. if (!token._startTimeQuery || !token._endTimeQuery) {
  112491. return -1;
  112492. }
  112493. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  112494. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  112495. result = timeEnd - timeStart;
  112496. this._deleteTimeQuery(token._startTimeQuery);
  112497. this._deleteTimeQuery(token._endTimeQuery);
  112498. token._startTimeQuery = null;
  112499. token._endTimeQuery = null;
  112500. }
  112501. else {
  112502. if (!token._timeElapsedQuery) {
  112503. return -1;
  112504. }
  112505. result = this._getTimeQueryResult(token._timeElapsedQuery);
  112506. this._deleteTimeQuery(token._timeElapsedQuery);
  112507. token._timeElapsedQuery = null;
  112508. token._timeElapsedQueryEnded = false;
  112509. this._currentNonTimestampToken = null;
  112510. }
  112511. return result;
  112512. }
  112513. return -1;
  112514. };
  112515. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  112516. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  112517. };
  112518. // We also need to update AbstractMesh as there is a portion of the code there
  112519. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  112520. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  112521. this._isOccluded = false;
  112522. return;
  112523. }
  112524. var engine = this.getEngine();
  112525. if (engine.webGLVersion < 2) {
  112526. this._isOccluded = false;
  112527. return;
  112528. }
  112529. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  112530. this._isOccluded = false;
  112531. return;
  112532. }
  112533. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  112534. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  112535. if (isOcclusionQueryAvailable) {
  112536. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  112537. this._isOcclusionQueryInProgress = false;
  112538. this._occlusionInternalRetryCounter = 0;
  112539. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  112540. }
  112541. else {
  112542. this._occlusionInternalRetryCounter++;
  112543. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  112544. this._isOcclusionQueryInProgress = false;
  112545. this._occlusionInternalRetryCounter = 0;
  112546. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  112547. // if strict continue the last state of the object.
  112548. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  112549. }
  112550. else {
  112551. return;
  112552. }
  112553. }
  112554. }
  112555. var scene = this.getScene();
  112556. if (scene.getBoundingBoxRenderer) {
  112557. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  112558. if (!this._occlusionQuery) {
  112559. this._occlusionQuery = engine.createQuery();
  112560. }
  112561. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  112562. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  112563. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  112564. this._isOcclusionQueryInProgress = true;
  112565. }
  112566. };
  112567. })(BABYLON || (BABYLON = {}));
  112568. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  112569. var BABYLON;
  112570. (function (BABYLON) {
  112571. /**
  112572. * Class used to generate noise procedural textures
  112573. */
  112574. var NoiseProceduralTexture = /** @class */ (function (_super) {
  112575. __extends(NoiseProceduralTexture, _super);
  112576. /**
  112577. * Creates a new NoiseProceduralTexture
  112578. * @param name defines the name fo the texture
  112579. * @param size defines the size of the texture (default is 256)
  112580. * @param scene defines the hosting scene
  112581. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  112582. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  112583. */
  112584. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  112585. if (size === void 0) { size = 256; }
  112586. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  112587. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  112588. _this._time = 0;
  112589. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  112590. _this.brightness = 0.2;
  112591. /** Defines the number of octaves to process */
  112592. _this.octaves = 3;
  112593. /** Defines the level of persistence (0.8 by default) */
  112594. _this.persistence = 0.8;
  112595. /** Gets or sets animation speed factor (default is 1) */
  112596. _this.animationSpeedFactor = 1;
  112597. _this._updateShaderUniforms();
  112598. return _this;
  112599. }
  112600. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  112601. var scene = this.getScene();
  112602. if (!scene) {
  112603. return;
  112604. }
  112605. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  112606. this.setFloat("brightness", this.brightness);
  112607. this.setFloat("persistence", this.persistence);
  112608. this.setFloat("timeScale", this._time);
  112609. };
  112610. NoiseProceduralTexture.prototype._getDefines = function () {
  112611. return "#define OCTAVES " + (this.octaves | 0);
  112612. };
  112613. /** Generate the current state of the procedural texture */
  112614. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  112615. this._updateShaderUniforms();
  112616. _super.prototype.render.call(this, useCameraPostProcess);
  112617. };
  112618. /**
  112619. * Serializes this noise procedural texture
  112620. * @returns a serialized noise procedural texture object
  112621. */
  112622. NoiseProceduralTexture.prototype.serialize = function () {
  112623. var serializationObject = {};
  112624. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  112625. serializationObject.brightness = this.brightness;
  112626. serializationObject.octaves = this.octaves;
  112627. serializationObject.persistence = this.persistence;
  112628. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  112629. serializationObject.size = this.getSize().width;
  112630. serializationObject.generateMipMaps = this._generateMipMaps;
  112631. return serializationObject;
  112632. };
  112633. /**
  112634. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  112635. * @param parsedTexture defines parsed texture data
  112636. * @param scene defines the current scene
  112637. * @param rootUrl defines the root URL containing noise procedural texture information
  112638. * @returns a parsed NoiseProceduralTexture
  112639. */
  112640. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  112641. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  112642. texture.brightness = parsedTexture.brightness;
  112643. texture.octaves = parsedTexture.octaves;
  112644. texture.persistence = parsedTexture.persistence;
  112645. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  112646. return texture;
  112647. };
  112648. return NoiseProceduralTexture;
  112649. }(BABYLON.ProceduralTexture));
  112650. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  112651. })(BABYLON || (BABYLON = {}));
  112652. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  112653. var __assign = (this && this.__assign) || function () {
  112654. __assign = Object.assign || function(t) {
  112655. for (var s, i = 1, n = arguments.length; i < n; i++) {
  112656. s = arguments[i];
  112657. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  112658. t[p] = s[p];
  112659. }
  112660. return t;
  112661. };
  112662. return __assign.apply(this, arguments);
  112663. };
  112664. var BABYLON;
  112665. (function (BABYLON) {
  112666. /**
  112667. * This can helps recording videos from BabylonJS.
  112668. * This is based on the available WebRTC functionalities of the browser.
  112669. *
  112670. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  112671. */
  112672. var VideoRecorder = /** @class */ (function () {
  112673. /**
  112674. * Create a new VideoCapture object which can help converting what you see in Babylon to
  112675. * a video file.
  112676. * @param engine Defines the BabylonJS Engine you wish to record
  112677. * @param options Defines options that can be used to customized the capture
  112678. */
  112679. function VideoRecorder(engine, options) {
  112680. if (options === void 0) { options = null; }
  112681. if (!VideoRecorder.IsSupported(engine)) {
  112682. throw "Your browser does not support recording so far.";
  112683. }
  112684. var canvas = engine.getRenderingCanvas();
  112685. if (!canvas) {
  112686. throw "The babylon engine must have a canvas to be recorded";
  112687. }
  112688. this._canvas = canvas;
  112689. this._canvas.isRecording = false;
  112690. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  112691. var stream = this._canvas.captureStream(this._options.fps);
  112692. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  112693. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  112694. this._mediaRecorder.onerror = this._handleError.bind(this);
  112695. this._mediaRecorder.onstop = this._handleStop.bind(this);
  112696. }
  112697. /**
  112698. * Returns wehther or not the VideoRecorder is available in your browser.
  112699. * @param engine Defines the Babylon Engine to check the support for
  112700. * @returns true if supported otherwise false
  112701. */
  112702. VideoRecorder.IsSupported = function (engine) {
  112703. var canvas = engine.getRenderingCanvas();
  112704. return (!!canvas && typeof canvas.captureStream === "function");
  112705. };
  112706. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  112707. /**
  112708. * True wether a recording is already in progress.
  112709. */
  112710. get: function () {
  112711. return !!this._canvas && this._canvas.isRecording;
  112712. },
  112713. enumerable: true,
  112714. configurable: true
  112715. });
  112716. /**
  112717. * Stops the current recording before the default capture timeout passed in the startRecording
  112718. * functions.
  112719. */
  112720. VideoRecorder.prototype.stopRecording = function () {
  112721. if (!this._canvas || !this._mediaRecorder) {
  112722. return;
  112723. }
  112724. if (!this.isRecording) {
  112725. return;
  112726. }
  112727. this._canvas.isRecording = false;
  112728. this._mediaRecorder.stop();
  112729. };
  112730. /**
  112731. * Starts recording the canvas for a max duration specified in parameters.
  112732. * @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.
  112733. * @param maxDuration Defines the maximum recording time in seconds.
  112734. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  112735. * @return a promise callback at the end of the recording with the video data in Blob.
  112736. */
  112737. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  112738. var _this = this;
  112739. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  112740. if (maxDuration === void 0) { maxDuration = 7; }
  112741. if (!this._canvas || !this._mediaRecorder) {
  112742. throw "Recorder has already been disposed";
  112743. }
  112744. if (this.isRecording) {
  112745. throw "Recording already in progress";
  112746. }
  112747. if (maxDuration > 0) {
  112748. setTimeout(function () {
  112749. _this.stopRecording();
  112750. }, maxDuration * 1000);
  112751. }
  112752. this._fileName = fileName;
  112753. this._recordedChunks = [];
  112754. this._resolve = null;
  112755. this._reject = null;
  112756. this._canvas.isRecording = true;
  112757. this._mediaRecorder.start(this._options.recordChunckSize);
  112758. return new Promise(function (resolve, reject) {
  112759. _this._resolve = resolve;
  112760. _this._reject = reject;
  112761. });
  112762. };
  112763. /**
  112764. * Releases internal resources used during the recording.
  112765. */
  112766. VideoRecorder.prototype.dispose = function () {
  112767. this._canvas = null;
  112768. this._mediaRecorder = null;
  112769. this._recordedChunks = [];
  112770. this._fileName = null;
  112771. this._resolve = null;
  112772. this._reject = null;
  112773. };
  112774. VideoRecorder.prototype._handleDataAvailable = function (event) {
  112775. if (event.data.size > 0) {
  112776. this._recordedChunks.push(event.data);
  112777. }
  112778. };
  112779. VideoRecorder.prototype._handleError = function (event) {
  112780. this.stopRecording();
  112781. if (this._reject) {
  112782. this._reject(event.error);
  112783. }
  112784. else {
  112785. throw new event.error;
  112786. }
  112787. };
  112788. VideoRecorder.prototype._handleStop = function () {
  112789. this.stopRecording();
  112790. var superBuffer = new Blob(this._recordedChunks);
  112791. if (this._resolve) {
  112792. this._resolve(superBuffer);
  112793. }
  112794. window.URL.createObjectURL(superBuffer);
  112795. if (this._fileName) {
  112796. BABYLON.Tools.Download(superBuffer, this._fileName);
  112797. }
  112798. };
  112799. VideoRecorder._defaultOptions = {
  112800. mimeType: "video/webm",
  112801. fps: 25,
  112802. recordChunckSize: 3000
  112803. };
  112804. return VideoRecorder;
  112805. }());
  112806. BABYLON.VideoRecorder = VideoRecorder;
  112807. })(BABYLON || (BABYLON = {}));
  112808. //# sourceMappingURL=babylon.videoRecorder.js.map
  112809. var BABYLON;
  112810. (function (BABYLON) {
  112811. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  112812. if (replace === void 0) { replace = false; }
  112813. // Dispose existing light in replace mode.
  112814. if (replace) {
  112815. if (this.lights) {
  112816. for (var i = 0; i < this.lights.length; i++) {
  112817. this.lights[i].dispose();
  112818. }
  112819. }
  112820. }
  112821. // Light
  112822. if (this.lights.length === 0) {
  112823. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  112824. }
  112825. };
  112826. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  112827. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112828. if (replace === void 0) { replace = false; }
  112829. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112830. // Dispose existing camera in replace mode.
  112831. if (replace) {
  112832. if (this.activeCamera) {
  112833. this.activeCamera.dispose();
  112834. this.activeCamera = null;
  112835. }
  112836. }
  112837. // Camera
  112838. if (!this.activeCamera) {
  112839. var worldExtends = this.getWorldExtends();
  112840. var worldSize = worldExtends.max.subtract(worldExtends.min);
  112841. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  112842. var camera;
  112843. var radius = worldSize.length() * 1.5;
  112844. // empty scene scenario!
  112845. if (!isFinite(radius)) {
  112846. radius = 1;
  112847. worldCenter.copyFromFloats(0, 0, 0);
  112848. }
  112849. if (createArcRotateCamera) {
  112850. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  112851. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  112852. arcRotateCamera.wheelPrecision = 100 / radius;
  112853. camera = arcRotateCamera;
  112854. }
  112855. else {
  112856. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  112857. freeCamera.setTarget(worldCenter);
  112858. camera = freeCamera;
  112859. }
  112860. camera.minZ = radius * 0.01;
  112861. camera.maxZ = radius * 1000;
  112862. camera.speed = radius * 0.2;
  112863. this.activeCamera = camera;
  112864. var canvas = this.getEngine().getRenderingCanvas();
  112865. if (attachCameraControls && canvas) {
  112866. camera.attachControl(canvas);
  112867. }
  112868. }
  112869. };
  112870. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  112871. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  112872. if (replace === void 0) { replace = false; }
  112873. if (attachCameraControls === void 0) { attachCameraControls = false; }
  112874. this.createDefaultLight(replace);
  112875. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  112876. };
  112877. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  112878. if (pbr === void 0) { pbr = false; }
  112879. if (scale === void 0) { scale = 1000; }
  112880. if (blur === void 0) { blur = 0; }
  112881. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  112882. if (!environmentTexture) {
  112883. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  112884. return null;
  112885. }
  112886. if (setGlobalEnvTexture) {
  112887. if (environmentTexture) {
  112888. this.environmentTexture = environmentTexture;
  112889. }
  112890. }
  112891. // Skybox
  112892. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  112893. if (pbr) {
  112894. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  112895. hdrSkyboxMaterial.backFaceCulling = false;
  112896. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  112897. if (hdrSkyboxMaterial.reflectionTexture) {
  112898. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112899. }
  112900. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  112901. hdrSkyboxMaterial.disableLighting = true;
  112902. hdrSkyboxMaterial.twoSidedLighting = true;
  112903. hdrSkybox.infiniteDistance = true;
  112904. hdrSkybox.material = hdrSkyboxMaterial;
  112905. }
  112906. else {
  112907. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  112908. skyboxMaterial.backFaceCulling = false;
  112909. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  112910. if (skyboxMaterial.reflectionTexture) {
  112911. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  112912. }
  112913. skyboxMaterial.disableLighting = true;
  112914. hdrSkybox.infiniteDistance = true;
  112915. hdrSkybox.material = skyboxMaterial;
  112916. }
  112917. return hdrSkybox;
  112918. };
  112919. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  112920. if (BABYLON.EnvironmentHelper) {
  112921. return new BABYLON.EnvironmentHelper(options, this);
  112922. }
  112923. return null;
  112924. };
  112925. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  112926. if (webVROptions === void 0) { webVROptions = {}; }
  112927. return new BABYLON.VRExperienceHelper(this, webVROptions);
  112928. };
  112929. })(BABYLON || (BABYLON = {}));
  112930. //# sourceMappingURL=babylon.sceneHelpers.js.map
  112931. 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"};
  112932. 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};"};
  112933. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  112934. globalObject["BABYLON"] = BABYLON;
  112935. //backwards compatibility
  112936. if(typeof earcut !== 'undefined') {
  112937. globalObject["Earcut"] = {
  112938. earcut: earcut
  112939. };
  112940. }
  112941. return BABYLON;
  112942. });